一个关于重构数组的问题

下面有如下数组:

const fData = [

{ownerName: "大厦a", type: "服务类型1", total: 85}

{ownerName: "大厦a", type: "服务类型2", total: 22}

{ownerName: "大厦b", type: "服务类型1", total: 11}

{ownerName: "大厦b", type: "服务类型2", total: 11}

{ownerName: "大厦c", type: "服务类型1", total: 121}

{ownerName: "大厦c", type: "服务类型2", total: 11}
]

希望重构成如下数组:

[{ownerName: "大厦a", "服务类型1": 85, "服务类型2": 22}

{ownerName: "大厦b", "服务类型1": 11, "服务类型2": 11}

{ownerName: "大厦c", "服务类型1": 121, "服务类型2": 11}

我目前进行如下代码:

let newName = map(uniq(ownerName), (item) => {
            return {
                ownerName: item,
            };
        });
        let newType = map(uniq(type), (item) => {
            return {
                type: item,
            };
        });

其中uniq和map是引用的第三方lodash的库。
往下就不知道该如何写了。求指导,谢谢

阅读 1.7k
2 个回答
const fData = [
  { ownerName: "大厦a", type: "服务类型1", total: 85 },
  { ownerName: "大厦a", type: "服务类型2", total: 22 },
  { ownerName: "大厦b", type: "服务类型1", total: 11 },
  { ownerName: "大厦b", type: "服务类型2", total: 11 },
  { ownerName: "大厦c", type: "服务类型1", total: 121 },
  { ownerName: "大厦c", type: "服务类型2", total: 11 },
]

let tmpObj = {}
for (let item of fData) {
  if (!tmpObj[item.ownerName]) {
    tmpObj[item.ownerName] = {}
  }
  tmpObj[item.ownerName][item.type] = item.total
}
let result = Object.entries(tmpObj).map(item => {
  item[1]['ownerName'] = item[0]
  return item[1]
})


----

同type的total累加?

let tmpObj = fData.reduce((accumulator, currentValue, currentIndex, array) => {
  if (!accumulator[currentValue.ownerName]) {
    accumulator[currentValue.ownerName] = {}
  }
  if (!accumulator[currentValue.ownerName][currentValue.type]) {
    accumulator[currentValue.ownerName][currentValue.type] = 0
  }
  accumulator[currentValue.ownerName][currentValue.type] += currentValue.total
  return accumulator
}, {})
let result = Object.entries(tmpObj).map(item => {
  item[1]['ownerName'] = item[0]
  return item[1]
})

设置一个map = {}
遍历fData
合并map[ownerName]信息
最后把map转成数组就好了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题