How to copy an object and get all its properties and their corresponding values in js

  • 2020-03-26 21:39:49
  • OfStack

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

If you knew all the properties of this object, you could just create a new one and assign values to each property, but what if you didn't? How do you create an object with the same content?
var obj={ colkey: "col", colsinfo: "NameList" } 

The easiest thing to do is to use for in,

For example, obj2 has exactly the same properties as obj
var obj2=new Object(); 
for(var p in obj) 
var name=p;//The attribute name
var value=obj[p];//The value of the property

In fact, this way has the certain limit, the key is in the js for have certain restriction, in does not traverse all attributes of the object, will only traversal can be enumerated attribute, by js method of defining the core can be enumerated, such as tostring (), but the attributes defined in the code are enumerable (through special can be defined as an enumeration). So this method is sufficient.

Whether an object can be used for in exhaustion can be determined by using the propertyIsEnumerable property, as follows:
PropertyIsEnumerable properties
Returns a Boolean value indicating whether the specified property is part of an object and whether the property is enumerable.
Object. PropertyIsEnumerable (proName)
The object
Will be options. An object.
Will be options. The string value of a property name.
If proName exists in object and you can use a For... If the In loop is exhausted, the propertyIsEnumerable property returns true. 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, while user-defined properties are always enumerable.
The propertyIsEnumerable property does not consider objects in the prototype chain.

Related articles: