Home  >  Article  >  Web Front-end  >  How to convert object into array in javascript

How to convert object into array in javascript

青灯夜游
青灯夜游Original
2021-11-19 17:28:0930158browse

Conversion method: 1. Define an empty array; 2. Use the "for (let i in obj){}" statement to traverse the object; 3. In the loop body, use the push() function to store the object elements into the array, the syntax is "let o = [];o[i] = obj[i];arr.push(o);".

How to convert object into array in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

For example, how to convert an object {'Unfinished':5, 'Completed':8, 'To be confirmed':4, 'Cancelled':6} is [{"Uncompleted":5},{"Completed":8},{"To be confirmed":4},{"Cancelled":6}].

Two ways to get values ​​for objects

We all know that there are two ways to get values ​​for objects in JS. You can get the value by adding the attribute name directly after ., which is what we most often use. One way, for example:

let obj = {name: 'yang'};
console.log(obj.name);  //yang

This is the most common way. There is another way that we don’t use too much, which is to use [] to wrap the attribute name to get the value, similar to an array, For example:

let obj = {name: 'yang'};
console.log(obj[‘name’]);  //yang

One thing to note here is that the contents in the square brackets are either variables or strings
What is the difference between the two? If for a known object, it is almost There is no difference.

Convert the object into an array

First look at our example

let obj = {'未完成':5, '已完成':8, '待确认':4, '已取消':6};
//将obj转化为
[{"未完成":5},{"已完成":8},{"待确认":4},{"已取消":6}]

1. The target array is just to get the set of keys or values ​​of the object

var arr = [];
for (let i in obj) {
    arr.push(i);        //key
    //arr.push(obj[i]); //值
}
console.log(arr);

2. Convert it to an array object according to the example we mentioned before. You only need to change the push content into an object.

var arr = [];
for (let i in obj) {
    let o = [];
    o[i] = obj[i];
    arr.push(o);
}
console.log(arr);

How to convert object into array in javascript

Finally, for (let i in obj){}, this method is mainly used to traverse objects, in is followed by the object, and i is the key.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to convert object into array in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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