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?
var obj={ colkey: "col", colsinfo: "NameList" }
The easiest way is to use for in,
For example, obj2 has exactly the same attributes as obj
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.