Eze*_*nda 10 javascript arrays associative-array map-function
我有一个具有以下格式的对象数组
[{'list': 'one', 'item': 1},
{'list': 'one', 'item': 2},
{'list': 'one', 'item': 3},
{'list': 'two', 'item': 1},
{'list': 'two', 'item': 2}]
Run Code Online (Sandbox Code Playgroud)
我想像这样改造它
[{'one': [1, 2, 3]},
{'two': [1, 2]}]
Run Code Online (Sandbox Code Playgroud)
我怎么能用Array.map函数呢?这是最好的选择吗?
Nin*_*olz 12
您可以使用Array.prototype.reduce
您的任务.它允许回调函数中的返回值用于下一次调用.
var data = [
{ 'list': 'one', 'item': 1 },
{ 'list': 'one', 'item': 2 },
{ 'list': 'one', 'item': 3 },
{ 'list': 'two', 'item': 1 },
{ 'list': 'two', 'item': 2 }
],
flat = data.reduce(function (r, a) {
r[a.list] = r[a.list] || [];
r[a.list].push(a.item);
return r;
}, {});
document.write('<pre>' + JSON.stringify(flat, 0, 4) + '</pre>');
Run Code Online (Sandbox Code Playgroud)
对于你的具体问题:
// Let x hold your array of objects.
res={}; // Create an empty object that will hold the answer
x.forEach (function (e) { // Use this function to iterate over each item in the list
res[e.list] = res[e.list] || []; // inspired by the Nina Scholz answer below
res[e.list].push(e.item); // Append the result to the array
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5294 次 |
最近记录: |