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);".
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}]
.
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.
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);
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!