簡體   English   中英

如何將對象數組轉換為鍵值對

[英]How to convert an array of objects into key value pairs

 var contacts = [
    { account: "Acme", firstName: "John", lastName: "Snow" },
    { account: "Metal Industries", firstName: "Ted", lastName: "Smith" },
    { account: "Acme", firstName: "Sara", lastName: "Butler" },
    { account: "HiTech Corp", firstName: "Sam", lastName: "Johnson" },
    { account: "HiTech Corp", firstName: "Arnold", lastName: "Williams" },
    { account: "Metal Industries", firstName: "Jessica", lastName: "Westcoat" },
    { account: "Acme", firstName: "Kyle", lastName: "Johnson" },
    { account: "HiTech Corp", firstName: "Jason", lastName: "Fernandez" }
  ];

目標是得到這個 output:

  result =  {
    "Acme": ["John Snow", "Kyle Johnson", "Sara Butler"],
    "HiTech Corp": ["Arnold Williams", "Jason Fernandez", "Sam Johnson"],
    "Metal Industries": ["Jessica Westcoat", "Ted Smith"]
  }

我下面的 function 不返回值數組,只返回最后一個值

  const convertArrayToObject = (array, key) => {
    const initialValue = {}
    return array.reduce((obj, item) => {
        return {...obj,[item[key]]: item,}
    }, initialValue)
  }

Output

任何幫助表示贊賞

const convertArrayToObject = (array, key) => {
    const initialValue = {}
    array.forEach((obj, item) => {
        initialValue[obj.account] = initialValue[obj.account] || []
        initialValue[obj.account].push(`${obj.firstName} ${obj.lastName}`)
    })
    return initialValue
}

你很接近,只是錯過了當你在結果數組中設置 object 時,你需要將它設置為一個數組 - 在這個腳本中是[k]: [v]而不是[k]: v

 var contacts = [ { account: "Acme", firstName: "John", lastName: "Snow" }, { account: "Metal Industries", firstName: "Ted", lastName: "Smith" }, { account: "Acme", firstName: "Sara", lastName: "Butler" }, { account: "HiTech Corp", firstName: "Sam", lastName: "Johnson" }, { account: "HiTech Corp", firstName: "Arnold", lastName: "Williams" }, { account: "Metal Industries", firstName: "Jessica", lastName: "Westcoat" }, { account: "Acme", firstName: "Kyle", lastName: "Johnson" }, { account: "HiTech Corp", firstName: "Jason", lastName: "Fernandez" } ]; const convertArrayToObject = (array, key) => { const initialValue = {} return array.reduce((obj, item) => { let k = item[key], v=item.firstName + ' ' + item.lastName; if (obj[k]) obj[k].push(v); else obj = {...obj, [k]: [v] } return obj }, initialValue) } console.log(convertArrayToObject(contacts, 'account'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM