猿问

关于数组 js

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到数组中

函数式编程
浏览 434回答 3
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);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答