2

Suppose i have an object whose values are arrays just like this:

obj = {
    'key1': [1,2],
    'key2': [3,4],
    'key3': [5,6],
}

How to i merge all the arrays of the object into one using concat. The number of keys of the object is dynamic of course but it will have at least one instance The desired output is this:

[1,2,3,4,5,6]

3 Answers 3

9

flat() on Object.values() is supposed to do the job:

const obj = {
        key1: [1,2],
        key2: [3,4],
        key3: [5,6]
      },
      merged = Object.values(obj).flat()

console.log(merged)
.as-console-wrapper{min-height:100%}

If being unlucky enough to deal with IE or Edge, one may fallback to reduce() for flattening:

const obj = {
        key1: [1,2],
        key2: [3,4],
        key3: [5,6]
      },
      merged = Object.keys(obj).reduce(function(r,k){     
        return r.concat(obj[k])
      }, [])

console.log(merged)
.as-console-wrapper{min-height:100%}

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

2 Comments

Or flatMap, I think flat works on arrays only, but he has an object with array properties.
Beware of flat support though. Worth mentioning that, in my opinion.
4
var obj={ 'key1': [1,2], 'key2': [3,4], 'key3': [5,6] };

var result = Object.values(obj)
    .reduce((accum, values) => {
        accum.push(...values);
        return accum;
    }, []);

console.log(result);

4 Comments

@Yevgens answer is better.
This answer has better broswer support though, so if for some reason OP needs to support IE and/or Edge this answer would be the correct one.
If we consider IE we must replace the spread operator ... to concat() so the result can be return accum.concat(values);
Or [].concat(...Object.values(obj)) and skip reduce entirely.
2

If you assume all the values of the object will an array you can make a Object.values() loop and concat each array.

const obj={
    'key1': [1,2],
    'key2': [3,4],
    'key3': [5,6],
};

const res = [];
for (const value of Object.values(obj)) {
    res.push(...value);
}
/// res: [1,2,3,4,5,6]

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.