I have a dynamic array of nested objects as below:
[
{
"fields": [
{
"field-1": {
"id": "field-1",
"value": "a1"
},
"field-2": {
"id": "field-2",
"value": "a2"
},
"field-3": {
"id": "field-3",
"value": "a3"
}
}
]
},
{
"fields": [
{
"field-1": {
"id": "field-1",
"value": "b1"
},
"field-2": {
"id": "field-2",
"value": "b2"
},
"field-3": {
"id": "field-3",
"value": "b3"
}
}
]
}
]
I want to parse/reduce this array to below kind of structure:
[
{
"field-1": "a1",
"field-2": "a2",
"field-3": "a3"
},
{
"field-1": "b1",
"field-2": "b2",
"field-3": "b3"
},
]
While I already have a verbose way of iterating over the array and constructing the new one, I wanted to know if it is possible to get the structure using the reduce method, as that would be faster?
4
Answers
You can use reduce to do it
You Can try this code
Here is my version:
Explanation
We first
flatMap()
the given array since we have array inside array, to get the following:Output:
Now for each object in the above array, I just need to change the value of each key in each object. So we need to call
map
on the previous output and for each object, generate our desired object usingreduce()
:Output:
The
JSON.parse
reviver andJSON.stringify
replacer can be used to modify nested values :