Push an object into an existing object

Viewed 420

I have an existing object and I want to push a new object into it with no property to target

So for instance:

  existingObj = { data: {postion: 1 } };
  objToPush = { person: [{ name: "Bella", age: 100}], about: { height: "1.70", weight: "170"} }

  end up with existingObj = { data: {postion: 1 }, person: [{ name: "Bella", age: 100}], about: { height: "1.70", weight: "170"} }

So I want to add objTopush into existingObj, but there is no property to target in existingObj

1 Answers

You can use spread syntax.

const existingObj = { data: { postion: 1 } };
const objToPush = {
  person: [{ name: 'Bella', age: 100 }],
  about: { height: '1.70', weight: '170' },
};
const ret = { ...existingObj, ...objToPush };
console.log(ret);

Related