Home > Net >  How to convert an array of objects into key value pairs
How to convert an array of objects into key value pairs

Time:12-02

 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:

  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

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

Output

Any help is appreciated

CodePudding user response:

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

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'))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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
}
  • Related