鍍金池/ 問答/HTML/ 關于數(shù)組 js

關于數(shù)組 js

let columns = ["name", "age", "weight"] // 里面的值是接口請求回來的,不固定有多少個的
let  data = [["jack", 18, 50],["jenny", 22, 60]] 
let  arr = []

//最后結(jié)果我想要這樣的

[
 {"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到數(shù)組中

回答
編輯回答
心沉
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);
2018年7月4日 11:44
編輯回答
深記你
        //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)

            //最后一次循環(huán)時,把total push到arr
            if (index == data.length - 1) arr.push(total)
            return total
        }, initValue)
2018年8月31日 11:47
編輯回答
不二心
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);
2017年11月6日 23:25