jquery 从数组中移除基于相同键的重复对象,并将它们的值添加到剩下的对象

7d7tgy0s  于 2022-12-12  发布在  jQuery
关注(0)|答案(2)|浏览(124)

考虑下面的javascript中的对象数组

const array = [
  { 10205: 2 },
  { 10207: 3 },
  { 10205: 2 },
  { 10207: 1 }
]

我想把它换成

array = [
  { 10205: 4 },
  { 10207: 4 }
]
0vvn1miw

0vvn1miw1#

const array = [{ 10205: 2 }, { 10207: 3 }, { 10205: 2 }, { 10207: 1 }];

const newArray = [];
array.forEach((element) => {
  const elementKey = Object.keys(element)[0];
  const foundIndex = newArray.findIndex((_) => Object.keys(_)[0] === elementKey);
  if (foundIndex >= 0) {
    newArray[foundIndex] =
        {[elementKey]: newArray[foundIndex][elementKey] + element[elementKey]};
  } else newArray.push(element);
});
console.log(newArray)
piah890a

piah890a2#

请使用reduce函数。

const array = [
      { 10205: 2 },
      { 10207: 3 },
      { 10205: 2 },
      { 10207: 1 }
    ]
    
    console.log(Object.values(array.reduce((acc, el)=>{
        Object.keys(el).map((key)=>{
            acc[key] = {
                [key]: (acc?.[key]?.[key] ?? 0) + el[key],
            }
        })
        return acc;
    }, {})));

相关问题