I got below array of object from response
[{
"pagination":
{
"count": 1
},
"products": [
{
"createdBy": "user1",
"status": 1,
}
]
},
{
"pagination": {
"count": 3
},
"products": [
{
"createdBy": "user2",
"status": 2,
},
{
"createdBy": "user3",
"status": 3,
}
]
}
}
]
I want to merge objects of array by keys - products and pagination. I want my final output to be like in below format
{
"products": [
{
"createdBy": "user1",
"status": 1,
},
{
"createdBy": "user2",
"status": 2,
},
{
"createdBy": "user3",
"status": 3,
}
]
}
Kindly help how to achieve this
CodePudding user response:
Use reduce
const array = [
{
"pagination": {
"count": 1
},
"products": [
{
"createdBy": "user1",
"status": 1
}
]
},
{
"pagination": {
"count": 3
},
"products": [
{
"createdBy": "user2",
"status": 2
},
{
"createdBy": "user3",
"status": 3
}
]
}
]
const result = array.reduce((tempArray,res)=>{
tempArray.push(...res.products)
return tempArray;
},[]);
console.log(result);
CodePudding user response:
You can try this out (where arr is your input array)
function getProducts() {
const newArr = arr.map(el => {
return el.products;
})
return {
products: newArr.flat()
}
}
getProducts();