Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple attributes to an existing js object

I want to add multiple attributes to an existing object with existing attributes. Is there a more concise way than one line per new attribute?

myObject.name = 'don';
myObject.gender = 'male';

Everything on MDN shows how to do new objects with bracket notation, but not existing objects: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

like image 457
Don P Avatar asked Aug 31 '25 15:08

Don P


1 Answers

In ES6/ ES2015 you can use the Object.assign method

let obj = {key1: true};
console.log('old obj: ', obj);
let newObj = {key2: false, key3: false};

Object.assign(obj, newObj);
console.log('modified obj: ', obj);
like image 149
Ed Barahona Avatar answered Oct 14 '25 01:10

Ed Barahona