I'm trying to reshape a JSON object in javascript using the reduce function.
As i understand, each time a new property is added to an object in javascript, it must be declared like ac['new_object'] = {};
. I'm doing this, so i don't understand why I'm seeing the error: Uncaught TypeError: Cannot set property 'title' of undefined
Reproducible example:
let field_list = [
{
"key": "id",
"val": {
"boost": 4
}
},
{
"key": "title",
"val": {
"boost": 4
}
}
]
field_list.reduce(function(ac, cu){
ac[cu.key] = {}
ac[cu.key] = cu.val
}, {})
How can i correctly reduce this JSON object? What was my error here?
Target format:
{
tales: {
foo: {"id": 2},
bar: {"title": 1},
...
}
}
Don't forget to return the accumulator object at the end of the function:
field_list.reduce(function(ac, cu){
ac[cu.key] = {}
ac[cu.key] = cu.val
return ac; // <---- added return statement
}, {})
Without that, undefined
will be implicitly returned, and so the next iteration of the loop will have ac
equal to undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With