Home > Back-end >  Combine two objects while keeping object name
Combine two objects while keeping object name

Time:11-17

I'm not totally sure if I'm using the correct terminology or not, I'm relatively new to node.

I have two JSON objects

const objA = {
  key1: value1
  ...
}

const objB = {
  key2: value2
 ...
}

that I want to combine into one while keeping the two object names, so it would look a bit like:

const newObj = {objA: { key1: value1,...}, objB: { key2: value2,...}}

So far in my research I've found Object.assign(objA,objB) which just combines them as newObj = {key1: value1, key2: value2, ...}

Is there a way to do what I want?

CodePudding user response:

const newObj = {objA, objB};

You can assign them into new object like above.

CodePudding user response:

Just putting it out there as a reference if you wanted to combine the key and values from both objects into one you could always use spread syntax if you decide to not go with a multi-level object:

const objA = {
  key1: "value1"
}

const objB = {
  key2: "value2"
}

const objCombined = {...objA, ...objB }

console.log(objCombined)

  • Related