let apiResponse = [{
id: 134,
user_name: 'abc',
phone_number: 1234567890,
sno: 'AM'
},
{
id: 948,
user_name: 'def',
phone_number: 9823437483,
sno: 'AM'
},
{
id: 865,
user_name: 'abc',
phone_number: 1234567890,
sno: 'PM'
},
{
id: 659,
user_name: 'ghi',
phone_number: 9834763467,
sno:'PM'
},
{
id: 456,
user_name: 'ghi',
phone_number: 9834763467,
sno:'AM'
},
{
id: 659,
user_name: 'ghi',
phone_number: 9834763467,
sno:'PM'
}]
Expected Output:
{
"AM": {
"134": {
id: 134,
user_name: 'abc',
phone_number: 1234567890,
sno: 'AM'
}
"948":{
id: 948,
user_name: 'def',
phone_number: 9823437483,
sno: 'AM'
}
"456":{
id: 456,
user_name: 'ghi',
phone_number: 9834763467,
sno:'AM'
}
}
"PM":{
"865": {
id: 865,
user_name: 'abc',
phone_number: 1234567890,
sno: 'PM'
}
"687":{
id: 687,
user_name: 'def',
phone_number: 9823437483,
sno: 'PM'
}
"659":{
id: 659,
user_name: 'ghi',
phone_number: 9834763467,
sno:'PM'
}
}
}
}
I am trying to manipulate an array of object into an object. I tried to create expected output by using external library lodash but sometime it crashes the web app. Also tried some other way but didn’t get the expected output. Getting problem in creating the nested object. first object key value will be the sno and the key of nested object is id
2
Answers
Solution without using Lodash using
Array.reduce()
:({})
as the accumulator(acc)
for thereduce
method.sno
value exists in the accumulator(acc[curr.sno])
. If not, it creates an empty object for thatsno
value. Then, it adds the current object to thatsno
object using the id as the key.The reduce method returns the final accumulator object as the output:
You could group by the wanted properties with nested object.