Home > Web Front-end > JS Tutorial > How to copy an object in js and get all its attributes and corresponding values ​​​​javascript skills

How to copy an object in js and get all its attributes and corresponding values ​​​​javascript skills

WBOY
Release: 2016-05-16 17:19:01
Original
1370 people have browsed it

How to copy an object in js, such as the following js object.

If you know all the attributes of this object, you can naturally create a new one, and then assign a value to each attribute. You can do it, but what if you don’t know? How to create an object with the same content?

Copy code The code is as follows:

var obj={ colkey: "col", colsinfo: "NameList" }

The easiest way is to use for in,

For example, obj2 has exactly the same attributes as obj
Copy code The code is as follows:

var obj2=new Object();
for(var p in obj)
{
var name=p;//Attribute name
var value=obj[p];//Value corresponding to the attribute
obj2[name]=obj[p];
}

In fact, this method has certain limitations. The key is that for in in js has certain limitations. It will not traverse all the properties of the object, but only the enumerable properties. The methods defined by the js core are not enumerable. For example, tostring(), but the properties defined in the code are all enumerable (can be specially defined as non-enumerable). Therefore this method is sufficient.

Whether an object can be exhaustively for in, we can judge it through the propertyIsEnumerable attribute. The description is as follows:
propertyIsEnumerable attribute
returns a Boolean value to indicate whether the specified property is part of an object. and whether the property is enumerable.
object.propertyIsEnumerable(proName)
Parameters
object
Required. an object.
proName
Required. A string value for the property name.
Description
The propertyIsEnumerable property returns true if proName exists in object and can be enumerated using a For...In loop. The propertyIsEnumerable property returns false if the object does not have the specified property or if the specified property is not enumerable. Typically, predefined properties are not enumerable, whereas user-defined properties are always enumerable.
propertyIsEnumerable property does not consider objects in the prototype chain.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template