0

I have two Objects one of them has the Store Name and the other object has the Price for an item along with the Store ID on both objects. Such as;

obj1 = [
    {id: 1,name: "Store1"},
    {id: 2,name: "Store2"},
    {id: 3,name: "Store3"}
  ];

obj2= [
{ id: 1, price: 100 },
{ id: 2, price: 200 },
{ id: 3, price: 300 }
];

What I want to achieve is that compare obj1 id with obj2 id if they are the same get the price and the store name from the same id. What is the best way to achieve this? I have been trying to use Array.map or filter but can't really make it work. Thank you!

Rinael
  • 133
  • 3
  • 12
  • 1
    Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Feb 08 '22 at 17:01
  • [Massive dupe](https://www.google.com/search?q=javascript+merge+two+object+arrays+on+key+site:stackoverflow.com) – mplungjan Feb 08 '22 at 17:03

1 Answers1

1

You can use map & find

const obj1 = [{
    id: 1,
    name: "Store1"
  },
  {
    id: 2,
    name: "Store2"
  },
  {
    id: 3,
    name: "Store3"
  },
  {
    id: 4,
    name: "Store3"
  }
];

const obj2 = [{
    id: 1,
    price: 100
  },
  {
    id: 2,
    price: 200
  },
  {
    id: 3,
    price: 300
  }
];

const newData = obj1.map((item, index) => {
  return {
    ...item,
    // if the item exist in obj2 then get the price else assign empty string
    price: obj2.find(elem => elem.id === item.id) ? .price || ''

  }


});
console.log(newData)
brk
  • 48,835
  • 10
  • 56
  • 78