简体   繁体   English

如何获取嵌套数组中所有同名字段的总和?

[英]How to the get the sum of all the field with the same name in a nested array?

I'm trying to find the sum of all the field values of the nested array, I suck at explaining stuffs like this, I hope the code below will give you some insight of what I want to do.我试图找到嵌套数组的所有字段值的总和,我很讨厌解释这样的东西,我希望下面的代码能让你对我想做的事情有所了解。

The array looks like this数组看起来像这样

data = [
    {
        id: 8434,
        name: listName, 
        data: [
            {name: "a name",
             quantity: 20,
            }
            {name: "another name",
             quantity: 40,
            }
            {name: "another new name",
             quantity: 40,
            }
        ]
    }, 
    {
        id: 54343,
        name: "new list name", 
        data: [
            {name: "a name",
             quantity: 12,
            }
            {name: "another name",
             quantity: 10,
            }
            {name: "another new name",
             quantity: 16,
            }
        ]
    }
]

This is how I want the data to be after carrying out the sum这就是我希望数据在执行总和后的样子

transformed = [
{name: "a name", quantity: 32},
{name: "another name", quantity: 50},
{name: "another new name", quantity: 56}
]

You can use Array.flatMap() followed by Array.reduce() to get the desired result.您可以使用Array.flatMap()后跟Array.reduce()来获得所需的结果。

We start by calling .flatMap() to get all the data values, then calling .reduce() on these to sum each value by name .我们首先调用 .flatMap() 来获取所有数据值,然后在这些上调用 .reduce() 以按name对每个值求和。

This will create an object, with a property for each name, we then call Object.values() to return to an array.这将创建一个对象,每个名称都有一个属性,然后我们调用Object.values()返回一个数组。

 const data = [ { id: 8434, name: 'listName', data: [ { name: "a name", quantity: 20, }, { name: "another name", quantity: 40, }, { name: "another new name", quantity: 40, } ] }, { id: 54343, name: "new list name", data: [ { name: "a name", quantity: 12, }, { name: "another name", quantity: 10, }, { name: "another new name", quantity: 16, } ] } ]; const transformed = Object.values(data.flatMap(({ data }) => data).reduce((acc, { name , quantity }) => { acc[name] = acc[name] || { name, quantity: 0 }; acc[name].quantity += quantity; return acc; }, {})) console.log('Transformed:', transformed)
 .as-console-wrapper { max-height: 100% !important; }

const transform = (data) => {
  const quantitySum = new Map()
  
  data.forEach(list => {
    list.data.forEach(({ name, quantity }) => {
      if (quantitySum.has(name)) {
        quantitySum.set(name, quantitySum.get(name) + quantity)
      } else {
        quantitySum.set(name, quantity)
      }
    })
  })
  
  return Array.from(quantitySum.entries())
    .map(([name, sum]) => ({
    name,
    quantity: sum
  }))
}

just loop them through and create a new object..只需循环它们并创建一个新对象..

const data = [
    {
        id: 8434,
        name: 'listName', 
        data: [
            {
                name: "a name",
                quantity: 20,
            },
            {
                name: "another name",
                quantity: 40,
            },
            {
                name: "another new name",
                quantity: 40,
            }
        ]
    }, 
    {
        id: 54343,
        name: "new list name", 
        data: [
            {
                name: "a name",
                quantity: 12,
            },
            {
                name: "another name",
                quantity: 10,
            },
            {
                name: "another new name",
                quantity: 16,
            }
        ]
    }
]


// Logic:
const transformed = []

data.forEach(d => {
    d.data.forEach(item => {
        const exist = transformed.find(t => t.name == item.name)
        if(exist) 
            exist.quantity += item.quantity
        else 
            transformed.push(item)
    })
})

console.log(transformed)

Output:输出:

[
  { name: 'a name', quantity: 32 },
  { name: 'another name', quantity: 50 },
  { name: 'another new name', quantity: 56 }
]

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

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