Home >Web Front-end >JS Tutorial >How to convert object to array in javascript
Method: 1. Use the "Array.from(object)" statement; 2. Use the "Object.values(object)" statement; 3. Use the "Object.keys(object)" statement; 4. Use the "Object.entries(object)" statement.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript object to array
1. Array.from() method , used for shallow copy of array. It is to convert an array-like object or traversable object into a real array.
eg:
let obj = { 0: ‘nihao‘, 1: ‘haha‘, 2: ‘gansha‘, ‘length‘: 3 } let arr = Array.from(obj) console.log(arr);
tips: 1. The object must have a length attribute, and the returned array length depends on the length length
2.key value Must be a numerical value
2. Object.values(object)
#tips: The difference from the first one is that the length attribute is not required and all enumerable objects of an object are returned. Attribute value
Here is a brief talk about enumerability. At present, I haven't understood the use of this enumerability. It probably means that each attribute of the
object has a description object, which is used to describe and control the behavior of the attribute. Use Object. getOwnPropertyDescriptor method to get the description object (set with Object.defineProperty method).
I will write about this enumerability after careful study in the future!
eg:
let obj = { 0: ‘nihao‘, 1: ‘haha‘, 2: ‘gansha‘, } let arr = Object.values(obj) console.log(arr);
3. Object.keys(object)
tips: Return an object An array composed of its own enumerable attributes. The order of the attribute names in the array is consistent with the order returned when using the for...in loop to traverse the object.
let obj = { 0: ‘nihao‘, 1: ‘haha‘, 2: ‘gansha‘, } let arr = Object.keys(obj) console.log(arr);
4 , Object.entries(object)
tips: Returns an array of key-value pairs of the enumerable properties of the given object itself
let obj = { 0: ‘nihao‘, 1: ‘haha‘, 2: ‘gansha‘, } let arr = Object.entries(obj) console.log(arr);
【 Related recommendations: javascript learning tutorial】
The above is the detailed content of How to convert object to array in javascript. For more information, please follow other related articles on the PHP Chinese website!