为了账号安全,请及时绑定邮箱和手机立即绑定

合并嵌套数组并对值求和

合并嵌套数组并对值求和

汪汪一只猫 2021-11-04 14:21:21
我有以下格式的数据,const data = [{        key:'key1',        rows:[          ["A","2018","B","1"],          ["A","2018","C","5"],          ["A","2018","B","4"],          ["A","2018","C","2"],        ]      },      {        key:'key1',        rows:[          ["A","2018","B","10"],          ["A","2018","C","50"],          ["A","2018","B","40"],          ["A","2018","C","20"],        ]      }]我想首先rows根据第三个值减少每个数组中的最后一个值并求和。输出应该是这样的const data = [{        key:'key1',        rows:[          ["A","2018","B","5"],          ["A","2018","C","7"]        ]      },      {        key:'key1',        rows:[          ["A","2018","B","50"],          ["A","2018","C","70"]        ]      }]在此之后,我想合并这两个对象并将rows. 最终输出应该是这样的const data = [{        key:'key1',        rows:[          ["A","2018","B","55"],          ["A","2018","C","77"]        ]      }]我试过这个,但没有得到想要的输出,data.map(data => ({          ...data,          rows: data.rows.reduce((array, value) => {            if(array.length > 0){              let found = false;              array.map(m => {                if(m[2] === value[2]){                  found = true;                  return [...m, m[3] = parseInt(m[3]) + parseInt(value[3])]                }              })              if(!found){                array.push(value)              }              return array            }else{              array.push(value)              return array            }          }, [])      }))
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

这样做的一种方法是遍历对象以获取行并将它们展平,然后reduce遍历数组以聚合它们,最后使用Object.values以获得正确的数据集。


const data = [{ key: 'key1', rows: [ ["A", "2018", "B", "1"], ["A", "2018", "C", "5"], ["A", "2018", "B", "4"], ["A", "2018", "C", "2"] ] }, { key: 'key1', rows: [ ["A", "2018", "B", "10"], ["A", "2018", "C", "50"], ["A", "2018", "B", "40"], ["A", "2018", "C", "20"]]}];


const key = data[0].key;


// Use `flatMap` to iterate over the object and merge the rows

const merged = data.flatMap(el => el.rows);


const rows = Object.values(merged.reduce((acc, c) => {

  const [ k1, k2, k3, k4 ] = c;

  acc[k3] = acc[k3] || [ k1, k2, k3, 0 ];

  acc[k3][3] += +k4;

  return acc;

}, {}));


console.log([{ key, rows }]);

注意:如果您需要将聚合数字返回到字符串,只需映射结果:


.map(([ a, b, c, d ]) => {

  return [ a, b, c, d.toString() ];

});


查看完整回答
反对 回复 2021-11-04
  • 1 回答
  • 0 关注
  • 177 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信