JS How to copy an object and get all of its properties and attributes corresponding to the value _javascript tips

Source: Internet
Author: User
How to copy an object in JS, such as a JS object as follows.

If you know that all the attributes of this object can be new again, and then assign a value to each attribute, you can do it, but what if you don't? How do I create an object with the same content?
Copy Code code as follows:

var obj={colkey: "Col", Colsinfo: "NameList"}

The simplest thing is to use for-in,

For example, OBJ2 has exactly the same attributes as obj
Copy Code code as follows:

var obj2=new Object ();
For (var p in obj)
{
Var name=p;//property Name
Value for Var value=obj[p];//property
OBJ2[NAME]=OBJ[P];
}

In fact, this way has a certain limit, the key is in the JS for a certain limit, and will not traverse all attributes of the object, will only traverse the enumerable properties, by the JS core defined methods are not enumerable, such as ToString (), However, the attributes defined in the code are enumerable (can be specifically defined as not enumerable). So this method is enough.

If an object can be used for in-exhaustive, we can judge by the propertyIsEnumerable attribute, as follows:
propertyIsEnumerable Property
Returns a Boolean value that indicates whether the specified property is part of an object and whether the property is enumerable.
Object.propertyisenumerable (Proname)
Parameters
Object
Required option. An object.
Proname
Required option. A string value for a property name.
Description
If proname exists in object and you can use a for ... The propertyIsEnumerable property returns True if the in loop is a poor lift. If object does not have the specified property or the specified property is not enumerable, then the propertyIsEnumerable property returns False. Typically, predefined properties are not enumerable, and user-defined attributes can always be enumerated.
The propertyIsEnumerable property does not consider objects in the prototype chain.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.