-2

I have two objects -

a = {0:"hai",1:"hello"}
b = {0:"what",1:"you"}

I want to get a resulting object on merge of the following format

c = {0:"hai",1:"hello",2:"what",3:"you"}

I tried different merge techniques, but fail to achieve this. What are the optimal ways of achieving the above?

1
  • I want the previous values to exist as well. None of the answers mentioned help . Commented Apr 24, 2020 at 12:12

2 Answers 2

1

Here's a solution that essentially converts the objects to arrays then merges them together using Array.prototype.concat:

Object.assign([], {0:"hai",1:"hello"}).concat(Object.assign([], {0:"what",1:"you"}))
Sign up to request clarification or add additional context in comments.

3 Comments

Above returns the array, whereas OP has requested an object
Arrays are just objects with more helper methods. If you really hate the helper methods then you can just throw in an Object.assign({}, stuff) where stuff is the code I posted above.
'...you can just' what I can do is whole lot better, however we're talking here about your solutions, which is, basically, a half of the answer
0

Universal approach for arbitrary number of input objects


Considering you want to merge your objects (with overlapping keys) in the order of appearance, I may suggest the following (works for arbitrary number of input objects)

Following is a live-demo as a proof of a concept:

const a = {0:"hai",1:"hello"},
      b = {0:"what",1:"you"},
      
      mergeObjects = (...args) => ({...args.flatMap(Object.values)}),
      
      c = mergeObjects(a,b)
      
console.log(c)
.as-console-wrapper{min-height:100%;}

However, since you don't seem to be making use of object keys and plain array may be what's desired, you may go as simple as that:

const a = {0:"hai",1:"hello"},
      b = {0:"what",1:"you"},
      
      mergeObjects = (...args) => args.flatMap(Object.values),
      
      c = mergeObjects(a,b)
      
console.log(c)
.as-console-wrapper{min-height:100%;}

Comments

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.