0

I want to update the first array's value on the basis of the second array.

For Example. This is my first Array

let a = [{id:"1",name:"none"},{id:"2",name:"two"}]

This is my second Array

let  b = [{id:"1",name:"one"}]

This is what I want as an output.

console.log(a)  //[{id:"1",name:"one"},{id:"2",name:"two"}]

Currently, I'm trying to achieve this by using array.filters and array.foreach but I'm getting an empty array.

a = a.filter((item) => {
      b.forEach(i => {
        if(item.id == i.id){
            return i 
        }else{
            return item
        }
    })
})

Ps. I don't want to create a new Array, I just want to update a's value on the basis of b. Thanks!

This is Test Case 2.

Array 1

let x = [
 {id:"1", status:"occupied"},
 {id:"2", status:"occupied"},
 {id:"3", status:"occupied"},
 {id:"4", status:"occupied"},
 {id:"5", status:"occupied"},
 {id:"6", status:"occupied"},
 {id:"7", status:"occupied"}
]

Array 2

let z = [
 {id:"1",status:"cleaning"},
 {id:"3",status:"cleaning"},
 {id:"5",status:"cleaning"},
 {id:"7",status:"cleaning"},
 {id:"2",status:"cleaning"},
]

Object.assign

let y = Object.assign(x,z);
console.log(y);//

I'm getting this output which is messed up.

{id: "1", status: "cleaning"}
{id: "3", status: "cleaning"}
{id: "5", status: "cleaning"}
{id: "7", status: "cleaning"}
{id: "2", status: "cleaning"}
{id: "6", status: "occupied"}
{id: "7", status: "occupied"}

3 Answers 3

4

You can use Object.assign which merges two objects by taking care of duplicates`

let c = Object.assign(a,b);
console.log(c);
Sign up to request clarification or add additional context in comments.

2 Comments

so easy, nice solution :-)
I tested your code it works fine for Test case 1 but for Test case 2 it doesn't work as expected. Kindly check Test case 2 in my edited question.
1

How about something like this:

const a = [{id:"1",name:"none"},{id:"2",name:"two"}];
const b = [{id:"1",name:"one"}];

for (const item of a) {
    const bFound = b.find(bItem => bItem.id === item.id);
  
  if (bFound) {
    item.name = bFound.name;
  }
}

console.log(a);

1 Comment

This works best for both of the Test Cases. Thanks for the help!
0

try this:

let a = [{id:"1",name:"none"},{id:"2",name:"two"}]
let  b = [{id:"1",name:"one"}]

var merge = (a, b, p) => a.filter( aa => ! b.find ( bb => aa[p] === bb[p]) ).concat(b)

console.log(merge(a, b, "id"))

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.