繁体   English   中英

node.js +对象数组

[英]node.js + Object Array

在我的节点应用程序中,我必须从另一个对象数组构造一个对象数组。

考虑我的对象数组为..

[ { id_0: 356, id_1: 33, name_1: 'aaaa' },
  { id_0: 756, id_1: 89, name_1: 'bbbbb' },
  { id_0: 456, id_1: 89, name_1: 'ccccc' },
  { id_0: 356, id_1: 27, name_1: 'dddd' } ]

我必须构造一个对象数组,如下所示:

[{
"356":["33":"aaaa","27":"ddddd"],------------->Changes made
"456":[{"89":"cccc"}],
"756":[{"89":"bbbbbbbb"}]
}]

我尝试使用async.map。但是我无法找到正确的方法。请帮助我解决此问题。谢谢...

您可以像这样使用Array.prototype.reduce函数

console.log(data.reduce(function(result, current) {
    var obj = {};
    result[current.id_0] = result[current.id_0] || [];
    obj[current.id_1] = current.name_1;
    result[current.id_0].push(obj);
    return result
}, {}));

产量

{ '356': [ { '33': 'aaaa' }, { '27': 'dddd' } ],
  '456': [ { '89': 'ccccc' } ],
  '756': [ { '89': 'bbbbb' } ] }

如果要将其转换为对象数组,只需使用[]包装data.reduce的结果,例如这样

console.log([data.reduce(function(result, current) {
    ...
    ...
}, {})]);

编辑:

result[current.id_0] = result[current.id_0] || [];

该行确保result[current.id_0]是一个数组。 如果result[current.id_0]的值是真实的,则返回该值,否则返回[] 因此,将创建一个新数组并将其分配给result[current.id_0] 它实际上是

if (result.hasOwnProperty(current.id_0) === false) {
    result[current.id_0] = [];
}

编辑2:如果您希望将分组的元素保留为对象,则可以这样

console.log(data.reduce(function(result, current) {
    result[current.id_0] = result[current.id_0] || {};
    result[current.id_0][current.id_1] = current.name_1;
    return result
}, {}));

产量

{ '356': { '27': 'dddd', '33': 'aaaa' },
  '456': { '89': 'ccccc' },
  '756': { '89': 'bbbbb' } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM