[英]go from array of objects to objects of array
Incoming Data传入数据
Node is an Array of Objects节点是一个对象数组
{
"db": {
"testing new apip": { "node": [] },
"testing new apip 5": {
"node": [
{
"id": "testing new id",
"time": 1571679839.6459858,
"rssi": "testing new rssi"
},
{
"id": "testing new id 5",
"time": 1571679845.8376184,
"rssi": "testing new rssi"
},
{
"id": "testing new id 55",
"time": 1571679851.4211318,
"rssi": "testing new rssi"
}
]
},
"testing new apip 52": {
"node": [
{
"id": "testing new id 556",
"time": 1571679859.927497,
"rssi": "testing new rssi"
}
]
}
}
}
I would like to know if there is a shortcut to appending to an array without using a for loop.我想知道是否有在不使用 for 循环的情况下附加到数组的快捷方式。
Basically I want to know what is the fastest way to convert基本上我想知道什么是最快的转换方式
var data2 = {
id: [],
time: [],
rssi: []
};
for (i = 0; i < data.db[AP[0]].node.length; i++) {
data2.id.push(data.db[AP[0]].node[0].id)
data2.time.push(data.db[AP[0]].node[0].time)
data2.rssi.push(data.db[AP[0]].node[0].rssi)
}
One approach is to use reduce() .一种方法是使用reduce() 。
// Array of objects. let node = [{ "id": "testing new id", "time": 1571679839.6459858, "rssi": "testing new rssi" }, { "id": "testing new id 5", "time": 1571679845.8376184, "rssi": "testing new rssi" }, { "id": "testing new id 55", "time": 1571679851.4211318, "rssi": "testing new rssi" } ]; let result = node.reduce((acc, curr) => { Object.entries(curr).forEach(([key, value]) => { acc[key] = acc[key] || []; acc[key].push(value); }); return acc; }, {}); // Object of arrays. console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.