在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ 關(guān)于數(shù)組 js

關(guān)于數(shù)組 js

let columns = ["name", "age", "weight"] // 里面的值是接口請(qǐng)求回來(lái)的,不固定有多少個(gè)的
let  data = [["jack", 18, 50],["jenny", 22, 60]] 
let  arr = []

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

[
 {"name": "jack","age": 18,"weight": 50},{"name": "jenny","age": 22,"weight": 60},{"name": "合計(jì)","age": 40,"weight": 110}
]

{"name": "合計(jì)","age": 40,"weight": 110} 最后一個(gè)是age跟weight進(jìn)行累積相加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];
}, ['合計(jì)', 0 , 0]);

arr.push(summary);
2018年7月4日 11:44
編輯回答
深記你
        //reduce的初始值
        const initValue = {}
        columns.forEach((param, index) => initValue[param] = index == 0 ? '合計(jì)' : 0);

        data.reduce((total, current, index) => {
            //合計(jì)累加
            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)時(shí),把total push到arr
            if (index == data.length - 1) arr.push(total)
            return total
        }, initValue)
2018年8月31日 11:47
編輯回答
不二心
let all = {
  name: "合計(jì)",
  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