You could merge the values of the object using Object.assign()
like this:
Object.assign({}, ...Object.values(response))
Explanation:
This is the syntax for Object.assign: Object.assign(target, source1, source2, ... etc)
. It basically takes all the properties from the source objects and updates the target object
The Object.values()
bit returns the value of the response
object. In this case, it's an array of objects like this:
[
{ names: ["John", "jim"] },
{ ages: [34, 24] }
]
You can spread the array and pass individual object as a parameter to Object.assign()
Here's a snippet:
let response = {
data1: {
names: ["John", "jim"]
},
data2: {
ages: [34, 24]
}
}
const output = Object.assign({}, ...Object.values(response))
console.log(output)
If it's too confusing you could use reduce
:
Object.values(response)
.reduce((a, v) => ({ ...a, ...v }), {})
Or a simple loop:
const output = {}
for(const key in response)
Object.assign(output, response[key])