1

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?

2 Answers 2

1
const newObj = {objA, objB};

You can assign them into new object like above.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I am an idiot. Can't tell you how long I've been trying to get this to work and completely missed the most obvious solution... Thanks!
@AndyReifman - Keep in mind that this creates a new object that references the original objA and objB so if you change the originals, those changes will be reflected in newObj also. That may or may not be what you want, but it's important to know what it is.
0

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)

3 Comments

It seems from the question that this is precisely what the OP doesn't want.
This doesn't keep the original object variable
Which was why I mentioned "putting it out there" in case he changes his approach or if this was referenced from a search query in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.