简体   繁体   English

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

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

If you have an array of objects like so:如果你有一个这样的对象数组:

在此处输入图像描述

What's the best way to add all numerical values in each object so each one looks something like this:在每个对象中添加所有数值的最佳方法是什么,所以每个对象看起来像这样:

{category: "A", total: 44}

So in the 0th item in the original array, 0+23+21 is 24, and is now represented by the new 'total' key.所以在原始数组的第 0 项中,0+23+21 是 24,现在由新的 'total' 键表示。

Bearing in mind that the 'keys' with numerical values in the original array eg 'col2' are randomly generated (so another array like the original can have keys like 'somethingelse'.请记住,原始数组中具有数值的“键”(例如“col2”)是随机生成的(因此,像原始数组这样的另一个数组可以具有“somethingelse”之类的键。

I've attempted it with the following, but I believe it's not written correctly:我已经尝试过以下方法,但我认为它写得不正确:

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

It may be good to know but the 'key' category always exists in each object and is fixed.知道可能很好,但“关键”类别始终存在于每个对象中并且是固定的。 All other key values are numerical and there'll always be more than one.所有其他键值都是数字的,并且总是不止一个。

Please check this.请检查这个。

 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)

You could use Array.map() along with Array.reduce() to sum the numeric values in the array.您可以使用Array.map()Array.reduce()对数组中的数值求和。

We'd create a toNumber() function to get the numeric value of any property.我们将创建一个toNumber()函数来获取任何属性的数值。 If this is not a number, it will return 0 (keeping the total unchanged).如果这不是数字,它将返回 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 = [{x:1}, {x:3}]

arr.reduce((accumulator, current) => accumulator + current.x, 0); 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}
]
**/

I think you are on the right way, you just need to do a bit more destructuring and type checking:我认为你走对了,你只需要做更多的解构和类型检查:

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

First, you map all objects to their representations as key-value-pairs.首先,您将所有对象映射到它们作为键值对的表示。 Then you iterate over these key-value pairs and keep all non-numerical values and their respective keys, while dropping key-value-pairs with a numerical value and replacing them by a property in which you aggregate the total value.然后迭代这些键值对并保留所有非数字值及其各自的键,同时删除具有数值的键值对并用聚合总值的属性替换它们。

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

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