迭代数组的每个对象,并在新数组中添加值

时间:2018-09-10 13:25:58

标签: javascript arrays

如果没有收到我要问的内容,请检查json和预期的输出。

"arrayData" = [{
        "id": "string",
        "label": "A1",
        "newData": [
            {
                "balance": 100,
            },
            {
                "balance": 200,
            },
            {
                "balance": 300,
            }
        ]
    },
    {
        "id": "string",
        "label": "A2",
        "newData": [
            {
                "balance": 100,
            },
            {
                "balance": 200,
            },
            {
                "balance": 300,
            }
        ]
    }]

预期输出:

 totalValueArray = [200,400,600]

1 个答案:

答案 0 :(得分:3)

我想我理解你在做什么
您想要对newData的每个索引0求和,将其推入数组
然后移至索引1,索引2 ...
一种方法是使用reduce + map,假设arrayData是您拥有的

let arrayData = [{
    "id": "string",
    "label": "A1",
    "newData": [
        {
            "balance": 100,
        },
        {
            "balance": 200,
        },
        {
            "balance": 300,
        }
    ]
  },
  {
    "id": "string",
    "label": "A2",
    "newData": [
        {
            "balance": 100,
        },
        {
            "balance": 200,
        },
        {
            "balance": 300,
        }
    ]
}];
    
let res = arrayData.reduce((acc, elem) => {
  elem.newData.map((n, i) => {
    if (acc[i]) {
      if (acc[i].balance) acc[i] = acc[i].balance + n.balance;
      else acc[i].balance = n.balance;
    } else acc.push(n);
  })
  return acc;
}, []);

console.log(res)