javascript 如何将字典数组整理成数组字典?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7455030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:11:14  来源:igfitidea点击:

how to collate an array of dictionaries into a dictionary of arrays?

javascript

提问by Terrence Brannon

I have this data:

我有这个数据:

list = [
      {name:'apple', category: "fruit", price: 1.22 },
      {name:'pear', category: "fruit", price: 2.22 },
      {name:'coke', category: "drink", price: 3.33 },
     {name:'sprite', category: "drink", price: .44 },
    ];

And I'd like to create a dictionary keyed on category, whose value is an array that contains all the products of that category. My attempt to do this failed:

我想创建一个以类别为键的字典,其值是一个包含该类别所有产品的数组。我尝试这样做失败了:

  var tmp = {};
    list.forEach(function(product) {
      var idx = product.category ;
      push tmp[idx], product;
    });
    tmp;

采纳答案by Jiri Kriz

function dictionary(list) {
    var map = {};
    for (var i = 0; i < list.length; ++i) {
        var category = list[i].category;
        if (!map[category]) 
            map[category] = [];
        map[category].push(list[i].name);  // add product names only
        // map[category].push(list[i]);    // add complete products
    }
    return map;
}
var d = dictionary(list);  // call

You can test it on jsfiddle.

您可以在jsfiddle对其进行测试。