-2

Is there a native js way to extend an object such that the original object is modified?

eg

const obj = {a: 1}
const obj2 = {b: "bar"}

such that obj returns {a:1, b: "bar"}. Or is this impossible and an new object has to be created?

Harry
  • 49,643
  • 70
  • 169
  • 251
  • 3
    First result when I search for _"javascript extend object"_ [Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) – Phil Feb 10 '19 at 23:12

1 Answers1

1

You can 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.

const obj = { a: 1 };
const obj2 = { b: 'bar' };

Object.assign(obj, obj2);

console.log(obj);
jo_va
  • 12,701
  • 3
  • 23
  • 44