js实现json数组根据某个字段高效简洁求和?

原始数组:

const result=[
  {
    "applyDepartmentName": "经济科",
    "materialName": "电脑",
    "normName": "小",
    "applyNum": 1,
    "applyAmount": 120,
    "supplierName": "联想",
    "purchaseNum": 0,
    "receiveNum": 0
  },
  {
    "applyDepartmentName": "医学科",
    "materialName": "口罩",
    "normName": "中",
    "applyNum": 3,
    "applyAmount": 960,
    "supplierName": "N95",
    "purchaseNum": 0,
    "receiveNum": 0
  },
  {
    "applyDepartmentName": "保卫科",
    "materialName": "脉冲器",
    "normName": "小",
    "applyNum": 2,
    "applyAmount": 110,
    "supplierName": "小米",
    "purchaseNum": 0,
    "receiveNum": 2
  }
]

期望数组:

const numList= [
        { name: '申请数量', key: 'applyNum', num:6 },
        { name: '申请金额', key: 'applyAmount', num: 1190 },
        { name: '采购数量', key: 'purchaseNum', num: 0 },
        { name: '领用数量', key: 'receiveNum', num: 2 },
      ],

大佬!!!

阅读 2.8k
2 个回答
const numList = [
    { name: '申请数量', key: 'applyNum', num: 0 },
    { name: '申请金额', key: 'applyAmount', num: 0 },
    { name: '采购数量', key: 'purchaseNum', num: 0 },
    { name: '领用数量', key: 'receiveNum', num: 0 },
].map(item => {
    item.num = result.reduce((num, citem) => num + (citem[item.key] || 0), 0)
    return item
})
const numList = [
    { name: "申请数量", key: "applyNum", num: 0 },
    { name: "申请金额", key: "applyAmount", num: 0 },
    { name: "采购数量", key: "purchaseNum", num: 0 },
    { name: "领用数量", key: "receiveNum", num: 0 },
];
result.forEach((item) => {
    numList.forEach((i) => {
        i.num += item[i.key];
    });
});
console.log(numList);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏