【问题标题】:Creating an associative array in JavaScript using the map function使用 map 函数在 JavaScript 中创建关联数组
【发布时间】:2015-12-13 04:25:37
【问题描述】:

我有一个具有以下格式的对象数组

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

【问题讨论】:

    标签: javascript arrays associative-array map-function


    【解决方案1】:

    您正在寻找分组方法。这个问题有一个很好的答案: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
       });
      

      【讨论】:

      • 您应该接受下面的 Nina Scholz 回答。它很优雅,不会改变结果变量,并提供reduce,非常值得学习。当/如果您学习函数式编程时,它会派上用场。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-17
        • 2017-08-02
        • 2016-11-15
        • 2015-02-14
        • 1970-01-01
        • 1970-01-01
        • 2015-11-15
        • 2010-09-25
        相关资源
        最近更新 更多