Javascript merge object children to a new object

I am trying to merge obj’s children to be a new object.

const obj = {
  "1": {"string1": "string11"},
  "2": {"string2": "string22"},
  "3": {"string33": "string33"},
  "4": {"string44": "string144"},
};

Object.assign is able to merge multiple objects can do this way:

Object.assign({}, obj[1], obj[2], obj[3], obj[4])

However, if obj is a dynamic object, more children objects would be added like

const obj = {
  "1": {"string1": "string11"},
  "2": {"string2": "string22"},
  "3": {"string3": "string33"},
  "4": {"string4": "string44"},
  "523": {"string5": "string55"}
  "more": {'something', "new string"}
  . . .
};

How to merge them automatically?

Answer

You can use the spread syntax:

Object.assign({}, ...Object.values(obj))

Leave a Reply

Your email address will not be published. Required fields are marked *