I have an array of objects coming from a formData serializeArray function. For example:
[
0 : {name: 'animal_monkey', value: 'banana'}
1 : {name: 'animal_horse', value: 'radishes'}
2 : {name: 'fruit_banana', value: 'yellow'}
3 : {name: 'fruit_apple', value: 'red'}
]
I am looking for a way to get these different elements into a single object, split by category with their appropriate value assigned, like so:
{
animal: {
monkey : banana,
horse : radishes
},
fruit: {
banana : yellow,
apple : red
}
}
I have tried doing this with reduce and Object assign, like so
obj = keys.map((k, i) => k.reduceRight((value, key) => ({[key]: value}), vals[i]) )
result = Object.assign({}, ...obj)
where keys is an array of ['animal_monkey', 'animal_horse', 'fruit_banana', 'fruit_apple'] and vals is a list with values: ['banana', 'radishes', 'yellow', 'red']. However, perhaps as expected, the values are overwritten and I end up with:
{
animal: {
horse : radishes
},
fruit: {
apple : red
}
}
The first value(s) don't survive the assignment. Does anyone have a good idea how to make this work?
Thanks!
{ type: 'animal', name: 'monkey', food: 'banana' }, for example. Might make things easier.