6

I have below two array of object in javascript

data1 = [
  {
    id: 123,
    option: "ABC",
    value: "123"
  },
  {
    id: 234,
    option: "DFG",
    value: "234"
  }
];

data2 = [
  {
    id: 123,
    option: "ABC",
    value: "123"
  }
];

When the id is match with 2nd array of object then i wanted to set the value(property) to 0 in first array of object for that particular id only. Like below once id 123 got match in both array then data1 array should look like this

data1 = [
  {
    id: 123,
    option: "ABC",
    value: "0"
  },
  {
    id: 234,
    option: "DFG",
    value: "234"
  }
];

How to achieve the above scenario ?

0

3 Answers 3

2

You can save the ids of data2 in a Set and iterate over data1 and change the value of each item if its id is in the set:

let data1 = [{ id: 123, option: 'ABC', value: "123" }, { id: 234, option: "DFG", value: "234" } ];
let data2 = [{ id: 123, option: 'ABC', value: "123" } ];
let set = new Set();
for(let i = 0; i < data2.length; i++)
     set.add(data2[i]['id'])
for(let i = 0; i < data1.length; i++)
     if(set.has(data1[i]['id']))
          data1[i]['value'] = 0;
console.log(data1)

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

Comments

2

You can make a set of all the object ids from the second array with a new Set(), and then .map() your first array to new objects, changing the value property if the object's id is within the set (checked using .has()):

const data1 = [{ id: 123, option: 'ABC', value: "123" }, { id: 234, option: "DFG", value: "234" } ];
const data2 = [{ id: 123, option: 'ABC', value: "123" }];

const idSet = new Set(data2.map(o => o.id));
const res = data1.map(o => ({...o, value: idSet.has(o.id) ? "0" : o.value}));
console.log(res);

Comments

0

You can make use of foreach, this will mutate your first array, which is what you need, or you can also make use of map(but it will generate new array):

var data1 = [{ id: 123, option: 'ABC', value: "123" }, { id: 234, option: "DFG", value: "234" } ];
var data2 = [ { id: 123, option: 'ABC', value: "123" } ];

data1.forEach(k=>{
  ispresent = data2.find(p=>p.id==k.id);
  if(ispresent) k.value = '0'
});

console.log(data1);

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.