关于数组 js

http404
  • 251
let columns = ["name", "age", "weight"] // 里面的值是接口请求回来的,不固定有多少个的
let  data = [["jack", 18, 50],["jenny", 22, 60]] 
let  arr = []

//最后结果我想要这样的

[
 {"name": "jack","age": 18,"weight": 50},{"name": "jenny","age": 22,"weight": 60},{"name": "合计","age": 40,"weight": 110}
]

{"name": "合计","age": 40,"weight": 110} 最后一个是age跟weight进行累积相加push到数组中

回复
阅读 477
3 个回答
✓ 已被采纳
        //reduce的初始值
        const initValue = {}
        columns.forEach((param, index) => initValue[param] = index == 0 ? '合计' : 0);

        data.reduce((total, current, index) => {
            //合计累加
            const item = {}
            columns.forEach((param, index) => {
                item[param] = current[index]
                //不是name的话,累加
                if (index != 0) total[param] += current[index]
            })
            //把current push到arr
            arr.push(item)

            //最后一次循环时,把total push到arr
            if (index == data.length - 1) arr.push(total)
            return total
        }, initValue)
let all = {
  name: "合计",
  age: 0,
  weight: 0
}

data.forEach(item => {
  arr.push(
    {
      name: item[0],
      age: item[1],
      weight: item[2]
    };
  all.age = all.age + item[1];
  all.weight = all.weight + item[2];
});
arr.push(all);
const summary = data.reduce((carry, item) => {
  arr.push({
    [columns[0]]: item[0],
    [columns[1]]: item[1],
    [columns[2]]: item[2],
  });

  carry[1] += item[1];
  carry[2] += item[2];
}, ['合计', 0 , 0]);

arr.push(summary);
你知道吗?

宣传栏