-2

Is it possible to add multiple properties at once without overwriting the properties which are already inside object?

object = {prop1: "1", prop1: "2", prop3: "3"};
//Want to add: {prop4: "4", prop5: "5", prop6: "6"} 

Is there any way to do this without iterating over the properties I want to add and adding one by one?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
juniorjunior
  • 69
  • 1
  • 11
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign –  Oct 02 '18 at 11:30

1 Answers1

1

Use Object assign

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

object = {prop1: "1", prop1: "2", prop3: "3"};
//Want to add: {prop4: "4", prop5: "5", prop6: "6"} 

Object.assign(object, {prop4: "4", prop5: "5", prop6: "6"})
console.log(object)
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
  • Great! Is it going to respect the order, won't add new properties before the ones that already exist inside object? – juniorjunior Oct 02 '18 at 11:33
  • 1
    @juniorjunior: I didn't quite follow you, but if you meant that it won't overwrite any existing properties if they already exist, then sorry it will. And that's what a looped code will do too. – Ashish Ranjan Oct 02 '18 at 11:36