M.Hassan Nasir
M.Hassan Nasir

Reputation: 851

Update first array on the basis of second in JavaScript

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"}

Upvotes: 0

Views: 242

Answers (3)

Rajdeep D
Rajdeep D

Reputation: 3900

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

let c = Object.assign(a,b);
console.log(c);

Upvotes: 4

JanuszO
JanuszO

Reputation: 1240

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

Upvotes: 0

Oliver
Oliver

Reputation: 45071

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

Upvotes: 1

Related Questions