[英]Converting an array of objects into an array node.js
I currently have an array of objects which is the following.我目前有一个对象数组,如下所示。
[
{ desc: '1', qty: '2', amt: '1', index: 0 },
{ desc: '1', qty: '2', amt: '1', index: 1 }
]
I need to turn this array of objects to something like that我需要把这个对象数组变成类似的东西
[
['1','2','1',0 ],
['1','2','1',1]
]
Any ideas?有任何想法吗?
You can use .map()
and Object.values()
:您可以使用.map()
和Object.values()
:
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.map()
方法创建一个新数组,其中填充了对调用数组中每个元素调用提供的 function 的结果。
The
Object.values()
method returns an array of a given object's own enumerable property values, in the same order as that provided by afor...in
loop.Object.values()
方法返回给定对象自身可枚举属性值的数组,其顺序与for...in
循环提供的顺序相同。 (The only difference is that afor...in
loop enumerates properties in the prototype chain as well.) (唯一的区别是for...in
循环也枚举原型链中的属性。)
Try as the following:尝试如下:
const data = [ { desc: '1', qty: '2', amt: '1', index: 0 }, { desc: '1', qty: '2', amt: '1', index: 1 } ] const result = data.map(e => Object.values(e)) console.log(result)
If the order of the properties in the object is guaranteed, you can use create a new array with Array.map()
, and use Object.values()
as the callback:如果保证 object 中属性的顺序,可以使用Array.map()
创建一个新数组,并使用Object.values()
作为回调:
const arr = [ { desc: '1', qty: '2', amt: '1', index: 0 }, { desc: '1', qty: '2', amt: '1', index: 1 } ] const result = arr.map(Object.values) console.log(result)
If the order of the properties in the objects might change, use Array.map()
, and then call Array.map()
again to extract the properties that you want in the the order you specify:如果对象中属性的顺序可能会发生变化,请使用Array.map()
,然后再次调用Array.map()
以按照您指定的顺序提取所需的属性:
const arr = [ { desc: '1', qty: '2', amt: '1', index: 0 }, { desc: '1', qty: '2', amt: '1', index: 1 } ] const order = ['desc', 'qty', 'amt']; // 'index' removed const result = arr.map(o => order.map(k => o[k])) console.log(result)
const data = [
{ desc: '1', qty: '2', amt: '1', index: 0 },
{ desc: '1', qty: '2', amt: '1', index: 1 }
];
var arr = [];
data.map(function(obj) {
arr.push(Object.values(obj))
});
console.log(arr) // value gets stored in arr object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.