1

I have an object that has the following structure:

mymain = { 
name1: [ {key1: number, key2: "string"},{key1: number, key2: "string"} ],
name2: [ {key1: number, key2: "string"},{key1: number, key2: "string"} ],
name3: [ {key1: number, key2: "string"},{key1: number, key2: "string"} ]
}

The top level items (name1, name2, name3) will vary in amount and key names.

I want to merge all the objects (which are also variable in number and values, but all have the same key structure) UNDER these names into one large object that will look like this:

Allconcat = [{key1: number, key2: "string"},{key1: number, key2: "string"},{key1: number, key2: "string"},{key1: number, key2: "string"},{key1: number, key2: "string"},{key1: number, key2: "string"}]

I have tried extracting the names of the top level items and them looping to concatenate the objects but that gives the wrong number of items:

var names = Object.keys(mymain)
    var firstname = names[0]
    names.shift() // should remove first item
    var firstObj = mymain[firstname] // name1 object
    var Allconcat
    console.log(firstObj) // correctly shows name1 with 2 keys
    for (var r = 0, rlen = names.length; r < rlen; r++) {
      Allconcat = firstObj.concat(mymain[names[r]])
    }
    console.log(Allconcat) // shows 4 objects, missing 2 in the middle, first and last are there

shifting or not shifting makes no difference, and I always end up with some of the elements missing in the middle.

1 Answer 1

2

One option is to take the Object.values of the mymain object, and flatten the array:

const mymain = { 
  name1: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ],
  name2: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ],
  name3: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ]
};

const Allconcat = Object.values(mymain).flat();
console.log(Allconcat);

Or, if you can't use .flat(), then spread into concat:

const mymain = { 
  name1: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ],
  name2: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ],
  name3: [ {key1: 'number', key2: "string"},{key1: 'number', key2: "string"} ]
};

const Allconcat = [].concat(...Object.values(mymain));
console.log(Allconcat);

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

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.