我有一个对象数组,格式如下
[{'list': 'one', 'item': 1},
{'list': 'one', 'item': 2},
{'list': 'one', 'item': 3},
{'list': 'two', 'item': 1},
{'list': 'two', 'item': 2}]
而我希望将它转换成这样
[{'one': [1, 2, 3]},
{'two': [1, 2]}]
我该如何使用Array.map函数来实现它?这是最好的选择吗?
我有一个对象数组,格式如下
[{'list': 'one', 'item': 1},
{'list': 'one', 'item': 2},
{'list': 'one', 'item': 3},
{'list': 'two', 'item': 1},
{'list': 'two', 'item': 2}]
而我希望将它转换成这样
[{'one': [1, 2, 3]},
{'two': [1, 2]}]
我该如何使用Array.map函数来实现它?这是最好的选择吗?
您可以使用 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>');
代码如下:
function groupBy(array, f)
{
var groups = {};
array.forEach(function(o)
{
var group = JSON.stringify(f(o));
groups[group] = groups[group] || [];
groups[group].push(o);
});
return Object.keys(groups).map(function(group)
{
return groups[group];
})
}
var result = groupBy(list, function(item)
{
return [item.lastname, item.age];
});
// 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
});
reduce
函数,学习它是非常有价值的。如果您开始学习函数式编程,它一定会派上用场的。 - Ram Rajamony