鍍金池/ 問答/數(shù)據(jù)分析&挖掘  HTML/ 一個關(guān)于重構(gòu)數(shù)組的問題

一個關(guān)于重構(gòu)數(shù)組的問題

下面有如下數(shù)組:

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}
]

希望重構(gòu)成如下數(shù)組:

[{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的庫。
往下就不知道該如何寫了。求指導,謝謝

回答
編輯回答
慢半拍

設(shè)置一個map = {}
遍歷fData
合并map[ownerName]信息
最后把map轉(zhuǎn)成數(shù)組就好了

2018年5月7日 13:48
編輯回答
風畔
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]
})
2018年1月18日 00:35