Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through one object, and set its values from another object

Say I have two objects:

let obj1 = {
  name: 'obj 1',
  id: 1,
  color: "#fff",
  pages: []
}

let obj2 = {
  name: 'obj 2',
  id: 2,
  color: "#ddd"
}

I want to write a function that follows this logic 'loop through obj1, and if both obj1 and obj1 have the same property, update obj1's property with obj2's value'

So result would return obj1 with the value:

{
  name: 'obj 2',
  id: 2,
  color: "#ddd",
  pages: []
}

I'm having a bit of an issue dealing with objects since I can't forEach or map them.

like image 257
cup_of Avatar asked Jun 21 '26 01:06

cup_of


1 Answers

You can use

var a = [obj1,obj2];
 obj1 = Object.assign(...a);

let obj1 = {
  name: 'obj 1',
  id: 1,
  color: "#fff",
  pages: []
}

let obj2 = {
  name: 'obj 2',
  id: 2,
  color: "#ddd"
}
var a = [obj1,obj2];
obj1 = Object.assign(...a);
console.log(obj1)
like image 131
Hien Nguyen Avatar answered Jun 22 '26 14:06

Hien Nguyen