简体   繁体   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" }
  ];

The goal is to get this output:目标是得到这个 output:

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

My function below is not returning the array of values and only returns the last value我下面的 function 不返回值数组,只返回最后一个值

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

Output Output

Any help is appreciated任何帮助表示赞赏

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
}

You were close, just missing that when you set up the object in the resultant array, you need to set it as an array - in this script that would be [k]: [v] and not [k]: v你很接近,只是错过了当你在结果数组中设置 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