繁体   English   中英

如何在对象数组中添加所有数字键值?

[英]How to add all numerical key-values in array of objects?

如果你有一个这样的对象数组:

在此处输入图像描述

在每个对象中添加所有数值的最佳方法是什么,所以每个对象看起来像这样:

{category: "A", total: 44}

所以在原始数组的第 0 项中,0+23+21 是 24,现在由新的 'total' 键表示。

请记住,原始数组中具有数值的“键”(例如“col2”)是随机生成的(因此,像原始数组这样的另一个数组可以具有“somethingelse”之类的键。

我已经尝试过以下方法,但我认为它写得不正确:

newArrayOfObjects.forEach(element => {
    Object.values(element).reduce((a, b) => a + b);
});

知道可能很好,但“关键”类别始终存在于每个对象中并且是固定的。 所有其他键值都是数字的,并且总是不止一个。

请检查这个。

 const array = [ { category: 'A', col1: 1, col2: 2, col3: 3, }, { category: 'B', col1: 2, col2: 3, col3: 4, } ] const result = array.map(obj => { const total = Object.values(obj).reduce((acc, value) => { if (typeof value === 'number') { return acc + value; } return acc; }, 0) return { category: obj.category, total } }) console.log(result)

您可以使用Array.map()Array.reduce()对数组中的数值求和。

我们将创建一个toNumber()函数来获取任何属性的数值。 如果这不是数字,它将返回 0(保持总数不变)。

 let arr = [ { a: 0, category: "a", col2: 23, col3: 21 }, { b: 0, category: "b", x: 100, y: 10, z: 1 }, { j: 0, category: "x", foo: 25, bar: 50, meta: 'content' }, ] function toNumber(n) { return isNaN(n) ? 0: n; } function sumTotals(a) { return a.map(({ category, ...obj}) => { const total = Object.values(obj).reduce((total, value) => { return total + toNumber(value); }, 0); return { category, total }; }) } console.log('Totals:', sumTotals(arr))
 .as-console-wrapper { max-height: 100% !important; }

arr = [{x:1}, {x:3}]

arr.reduce((accumulator, current) => accumulator + current.x, 0);

var data = [
    { "category": "A", "col0": 5, "col1": 8, "some": "thing"},
    { "category": "B", "col1": 3, "col2": 5}
];

var res = data.map((it) => {
    const { category, ...rest } = it;
    return {
      ...it,
      total: Object.values(rest).reduce(
        (prev, curr) =>
          typeof curr === "number" ? prev + curr : prev, // add if the current value is numeric
          0
      )
    }
});

console.log(res);

/**
[
  {"category":"A","col0":5,"col1":8,"some":"tst","total":13}, 
  {"category":"B","col1":3,"col2":5,"total":8}
]
**/

我认为你走对了,你只需要做更多的解构和类型检查:

const aggregated = newArrayOfObjects.map((obj) =>
  Object.entries(obj).reduce(
    (newObj, [key, value]) => ({
      ...newObj,
      ...(typeof value === "number"
        ? { total: newObj.total + value }
        : { [key]: value }),
    }),
    { total: 0 }
  )
);

首先,您将所有对象映射到它们作为键值对的表示。 然后迭代这些键值对并保留所有非数字值及其各自的键,同时删除具有数值的键值对并用聚合总值的属性替换它们。

暂无
暂无

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

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