0

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

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.