繁体   English   中英

如何基于在对象数组中共享另一个属性名称的值来对一个属性名称的值求和(在 Javascript 中)

[英]How to sum the values of one property name based on sharing the value of another property name in an array of objects (in Javascript)

我有数百个对象的数组,其结构如下:

[
        {
          "type": "apples",
          "count": 10
        },
        {
          "type": "oranges",
          "count": 20
        },
        {
          "type": "apples",
          "count": 5
        },
        {
          "type": "grapes",
          "count": 20
        },
        {
          "type": "grapes",
          "count": 10
        }
]

如果它们共享相同的类型,我需要遍历它们并创建一个组合计数的新数组。 所以上面例子中的 output 需要是:

[
        {
          "type": "apples",
          "count": 15
        },
        {
          "type": "oranges",
          "count": 20
        },
        {
          "type": "grapes",
          "count": 30
        },
]

任何帮助将不胜感激。

function checkExist(type) {
  for(let i = 0; i < newArr.length; i++) {
    if(newArr[i].type == type) {
      return i;
    }
  }
  return false;    
}

let arr = [
  {
    "type": "apples",
    "count": 10
  },
  {
    "type": "oranges",
    "count": 20
  },
  {
    "type": "apples",
    "count": 5
  },
  {
    "type": "grapes",
    "count": 20
  },
  {
    "type": "grapes",
    "count": 10
  }
];

let newArr = [];

for(let i = 0; i < arr.length; i++) {
  let index = checkExist(arr[i].type);
  if( index === false) {
    newArr.push(arr[i]);
  }else {
    newArr[index].count += arr[i].count;  
  }
}

console.log(newArr);

怎么样:

const data = [
  {
    type: 'apples',
    count: 10
  },
  {
    type: 'oranges',
    count: 20
  },
  {
    type: 'apples',
    count: 5
  },
  {
    type: 'grapes',
    count: 20
  },
  {
    type: 'grapes',
    count: 10
  }
];

const types = data.map((food) => food.type);
const uniqueTypes = [...new Set(types)];

const counts = uniqueTypes.map((foodType) => ({
  type: foodType,
  count: data
    .filter((food) => food.type === foodType)
    .map((food) => food.count)
    .reduce((acc, currCount) => acc + currCount, 0)
}));

我会使用减少。 请注意,此解决方案使用 ES6 语法。

 let values = [ { "type": "apples", "count": 10 }, { "type": "oranges", "count": 20 }, { "type": "apples", "count": 5 }, { "type": "grapes", "count": 20 }, { "type": "grapes", "count": 10 } ] let collatedValues = values.reduce((accumulator, currentValue) => { let existing = accumulator.find(n => n.type === currentValue.type); if (existing) { existing.count += currentValue.count } else { accumulator.push(currentValue) } return accumulator },[]) console.log(collatedValues)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM