How to group or merge this array of objects in javascript?

前端 未结 8 819
悲&欢浪女
悲&欢浪女 2020-12-18 23:22

I have an array of objects like below for example.

{name: \"Mc Donald\", quantity: 4, maleCount: 1, femaleCount: 0}
{name: \"KFC\", quantity: 9, maleCou         


        
相关标签:
8条回答
  • 2020-12-18 23:58

    My solution based on reduce:

    let data = [
      {name: "Mc Donald", quantity: 4, maleCount: 1, femaleCount: 0},
      {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
      {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
      {name: "Mc Donald", quantity: 4, maleCount: 0, femaleCount: 1},
      {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
      {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
      {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
      {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
    ];
    
    // We will only keep an array of values of the merged object
    let result = Object.values(
      // Merge data to name indexed objects
      data.reduce((p,c) => {
        // Ensure key (name) exists
        if (!p[c.name]) {
           // If first occurence, duplicate object (to avoid modification of original array)
           p[c.name] = Object.assign({}, c);
        } else {
           // If key (name) already exists, sum up relevant attributes
           p[c.name].quantity += c.quantity;
           p[c.name].maleCount += c.maleCount;
           p[c.name].femaleCount += c.femaleCount;
        }
        // return updated object
        return p;
      }, {})
    );
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    hope this will help

    0 讨论(0)
  • 2020-12-18 23:58

    check this code below:

    var array = [
        {name: "Mc Donald", quantity: 4, maleCount: 1, femaleCount: 0},
        {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
        {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
        {name: "Mc Donald", quantity: 4, maleCount: 0, femaleCount: 1},
        {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
        {name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
        {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
        {name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
    ];
    
    var result = [];
    
    for(var index in array){
        var obj = array[index];
        if(result.hasOwnProperty(obj.name)) {
            result[obj.name].quantity += obj.quantity;
            result[obj.name].maleCount += obj.maleCount;
            result[obj.name].femaleCount += obj.femaleCount;
        }else{
            result[obj.name] = {};
            result[obj.name].quantity = obj.quantity;
            result[obj.name].maleCount = obj.maleCount;
            result[obj.name].femaleCount = obj.femaleCount;
        }
    }
    
    console.log(result);
    
    0 讨论(0)
提交回复
热议问题