首页 > 解决方案 > 对对象类型数组的属性求和并将它们作为单个对象加入

问题描述

需要根据主题名称属性对不同对象的score和求和。total_score

输入数据 :

var data = [{
  name: "One",
  maths: {
    score: 2,
    total_score: 4
  },
  science: {
    score: 2,
    total_score: 4
  },
  social: {
    score: 2,
    total_score: 4
  }
}, {
  name: "One",
  maths: {
    score: 3,
    total_score: 4
  },
  science: {
    score: 1,
    total_score: 4
  },
  english: {
    score: 4,
    total_score: 4
  }
}]

预期输出:

{
  name: "One",
  maths: {
    score: 5,
    total_score: 8
  },
  science: {
    score: 3,
    total_score: 8
  },
  social: {
    score: 2,
    total_score: 4
  },
  english: {
    score: 4,
    total_score: 4
  }
}

我试过这个:

data.forEach(function (a) {
    if (!this[a.name]) {
        this[a.name] = { name: a.name, contributions: 0 };
        result.push(this[a.name]);
    }
    this[a.name].contributions += a.contributions;
}, Object.create(null));

但这不适用于我的情况。对象不同的地方,contributions即主题名称每次都不同。

先谢谢各位了!

标签: javascriptarraysnode.jsjson

解决方案


您可以使用Array.reduce()

var data = [{
    name: "One",
    maths: {
      score: 2,
      total_score: 4
    },
    science: {
      score: 2,
      total_score: 4
    },
    social: {
      score: 2,
      total_score: 4
    }
  },
  {
    name: "One",
    maths: {
      score: 3,
      total_score: 4
    },
    science: {
      score: 1,
      total_score: 4
    },
    english: {
      score: 4,
      total_score: 4
    }
  },
  {
    name: "Two",
    maths: {
      score: 3,
      total_score: 4
    },
    science: {
      score: 1,
      total_score: 4
    },
    english: {
      score: 4,
      total_score: 4
    }
  },
  {
    name: "Two",
    maths: {
      score: 3,
      total_score: 5
    },
    science: {
      score: 1,
      total_score: 5
    },
    english: {
      score: 4,
      total_score: 6
    }
  }
];
var res = data.reduce((acc, item)=>{
  var exist = acc.find(({name}) => name === item.name);
  if(exist){
    Object.keys(item).forEach((key) =>{
      if(key !== 'name'){
        if(exist[key]){
          exist[key].total_score += item[key].total_score;
          exist[key].score += item[key].score
        } else {
           exist[key] = item[key]
        }
      }
    });
  } else {
    acc.push(item);
  }
  return acc;
}, []);
console.log(res);


推荐阅读