使用map函数在JavaScript中创建关联数组

13

我有一个对象数组,格式如下

[{'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函数来实现它?这是最好的选择吗?

3个回答

18

您可以使用 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>');


2
你需要一个按组排序的方法。这个问题有一个很好的答案:https://codereview.stackexchange.com/questions/37028/grouping-elements-in-array-by-multiple-properties

代码如下:

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];
});

2
针对您的具体问题:
// 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
 });

2
你应该接受下面的Nina Scholz答案。它很优雅,不会改变结果变量,并提供了reduce函数,学习它是非常有价值的。如果您开始学习函数式编程,它一定会派上用场的。 - Ram Rajamony

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接