Javascript:如何获取数组中相同对象的数量?

时间:2020-07-28 08:43:16

标签: javascript json

这是我的json对象。我在其中存储对象ID和对象类型。

let jsonData = [
   {"id": "1", "object": "pen"}, 
   {"id": "4", "object": "bag"}, 
   {"id": "2", "object": "paper"}, 
   {"id": "5", "object": "bottle"},
   {"id": "3", "object": "notepad"}, 
   {"id": "1", "object": "pen"}, 
   {"id": "4", "object": "bag"}, 
   {"id": "3", "object": "notepad"}, 
   {"id": "3", "object": "notepad"}, 
   {"id": "1", "object": "pen"}, 
   {"id": "2", "object": "paper"},
   {"id": "1", "object": "pen"},      
]

因此,现在我想使用以下格式的上述数组创建一个新数组:

|---------------------|------------------|
|        Object       |        Unit      |
|---------------------|------------------|
|         Pen         |         4        |
|---------------------|------------------|
|         Paper       |         2        |
|---------------------|------------------|
|        Notepad      |         3        |
|---------------------|------------------|
|         Bag         |         2        |
|---------------------|------------------|
|        Bottle       |         1        |
|---------------------|------------------|

简而言之,新数组应显示所有对象及其计数值。 预先感谢。

1 个答案:

答案 0 :(得分:1)

只需使用Array.reduce函数

 let jsonData = [
      {"id": "1", "object": "pen"}, 
      {"id": "4", "object": "bag"}, 
      {"id": "2", "object": "paper"}, 
      {"id": "5", "object": "bottle"},
      {"id": "3", "object": "notepad"}, 
      {"id": "1", "object": "pen"}, 
      {"id": "4", "object": "bag"}, 
      {"id": "3", "object": "notepad"}, 
      {"id": "3", "object": "notepad"}, 
      {"id": "1", "object": "pen"}, 
      {"id": "2", "object": "paper"},
      {"id": "1", "object": "pen"},      
   ];

   let summary = jsonData.reduce( (ac, el) => {

    let obj = ac.find(e => e.object == el.object);

    if (!obj) {
      obj = {object: el.object, unit: 0};
      ac.push(obj);
    }

    obj.unit = obj.unit + 1;
    return ac;
   }, []);
   
   console.log(summary);