Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge two array of objects and return some keys only in JavaScript

I want to merge two object arrays based on itemId into one object array with only some specific key.

I managed to merge it but it contains all the keys from both object arrays. I only want the orderId, name and itemName.

const arrOrder = [
  { orderId: 1, userId: 1, name: "Zack", itemId: 100 },
  { orderId: 2, userId: 2, name: "Robin", itemId: 200 }
];

const arrItem = [
  { itemId: 100, itemName: "Fruits", itemDescription: "Apple and Oranges" },
  { itemId: 200, itemName: "Snacks", itemDescription: "Potato Chips and Nuts" }
];

const mergedArray = arrOrder.map((order) => {
  const matchedObject = arrItem.find((item) => item.itemId === order.itemId);
  return { ...order, ...matchedObject };
});

console.log(mergedArray);

My desired result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{
  orderId: 1,
  name: 'Zack',
  itemName: 'Fruits'
}, {
  orderId: 2,
  name: 'Robin',
  itemName: 'Snacks'
}]

Which line of code can I change so that the merged object array only contains the key that I wanted?

I tried to do this way but to no avail.

const mergedArray = arrOrder.map((order) => {
  const matchedObject = arrItem.find((item) => item.itemId === order.itemId);
  return { order.id, order.name, matchedObject.itemName };
});

>Solution :

The issue is because you’re using the spread operator, which will include every property by default.

If you don’t want that then can instead manually specify the property names to include and give them a value:

return {
  orderId: order.orderId,
  name: order.name,
  itemName: matchedObject.itemName
};

Here’s a full working example:

const arrOrder = [
  { orderId: 1, userId: 1, name: "Zack", itemId: 100 },
  { orderId: 2, userId: 2, name: "Robin", itemId: 200 }
];

const arrItem = [
  { itemId: 100, itemName: "Fruits", itemDescription: "Apple and Oranges" },
  { itemId: 200, itemName: "Snacks", itemDescription: "Potato Chips and Nuts" }
];

const mergedArray = arrOrder.map((order) => {
  const matchedObject = arrItem.find((item) => item.itemId === order.itemId);
  return {
    orderId: order.orderId,
    name: order.name,
    itemName: matchedObject.itemName
  };
});

console.log(mergedArray);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading