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)
}
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
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'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.