2014-04-09 40 views
0

在我的节点应用程序中,我必须从另一个对象数组构造一个对象数组。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.But我不能得到正确的方式请帮我解决这个问题。预先感谢...

+0

在这里使用'async'有什么意义? –

+0

它是Array.map()不是'async.map()',你通常不会这样调用它,而是作为一个数组实例的方法。 – Paul

回答

4

你可以用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' } } 
+0

@Subburaj请检查编辑,让我知道,如果你需要进一步澄清:) – thefourtheye

+0

@Subburaj你的意思是'{ “33”: “AAAA”, “27”: “DDDDD”}'?因为这在这里会非常合适? – thefourtheye

+0

@Subburaj请检查最新的答案。 – thefourtheye