js同一个数组对象怎么判断对象里面的值相同去重组一个新数组对象?

如下有一个数组对象:

const arr = [
    {
        secondType: "原料成本",
        templateKey: "ratio",
        templateSort: 0,
        templateValue: '10%',
        thirdType: "原料成本总计"
    },
    {
        secondType: "原料成本",
        templateKey: "cost",
        templateSort: 0,
        templateValue: "5",
        thirdType: "原料成本总计"
    },
    {
        secondType: "原料成本",
        templateKey: "ratio",
        templateSort: 1,
        templateValue: null,
        thirdType: "原料成本总计"
    },
    {
        secondType: "原料成本",
        templateKey: "cost",
        templateSort: 1,
        templateValue: "3",
        thirdType: "原料成本总计"
    }
]

需要组成一个新数组是这样:

const newArr = [
    {
        ratio:'10%',
        cost:'5',
    },
    {
        ratio:null,
        cost:'3'
    },
]

新数组newArr是以arr的templateKey作为自己的key,然后根据templateSort是否相同放在同一个对象,如
image.png
大家有什么好的办法

阅读 1.7k
1 个回答
Object.values(arr.reduce((obj, item) => {
    if(!obj[item.templateSort]){
        obj[item.templateSort] = {}
    }
    obj[item.templateSort][item.templateKey] = item.templateValue
    return obj
}, {}))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题