user1094081
user1094081

Reputation:

Concatenate Object values

I have a JavaScript Object and I'm sure the value of any key is an array (even empty in some case):

{key1:["a","b","c"],key2:["d","e","f"],key3:...}

Aside from using Underscore, is there any way to concatenate all the values of this Object (and create a new array)?

At the moment I get the keys name using Object.keys, then I loop and concatenate.

Any help is appreciated.

Upvotes: 9

Views: 32251

Answers (4)

robe007
robe007

Reputation: 3927

A simple approach is to get the values using Object.values() and concatenate them with [].concat.apply() in this way:

const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }

const _arr = [].concat.apply([], Object.values(_obj))

console.log(_arr)


Another similar way, is to merge Object.values() by spreading them into Array.concat() like this:

const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }

const _arr = [].concat(...Object.values(_obj))

console.log(_arr)


Also reducing each value of the Object.values() and concatenate them, you can get the same result:

const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }

const _arr = Object.values(_obj).reduce((r,c) => r.concat(c), [])

console.log(_arr)


To finish, you can also use Array.prototype.flat() over each value of the Object.values(). Just keep in mind: it's not supported on all browsers.

const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }

const _arr = Object.values(_obj).flat()

console.log(_arr)

Hope this methods could help someone out there :)

Upvotes: 14

Aliaksei Shytkin
Aliaksei Shytkin

Reputation: 415

var obj = {key1:["a","b","c"],key2:["d","e","f"]};

var arr = Object.keys(obj).reduce(function(res, v) {
    return res.concat(obj[v]);
}, []);

// ["a", "b", "c", "d", "e", "f"]

Upvotes: 13

Rakesh_Kumar
Rakesh_Kumar

Reputation: 1442

Try this: http://jsfiddle.net/6hbp5bzo/

var arr= [];
var o={key1:["a","b","c"],key2:["d","e","f"]}
for(key in o){
  if(o.hasOwnProperty(key)){
    arr.push(o[key]);
}
}
alert(arr);

Upvotes: 1

Ivan Sivak
Ivan Sivak

Reputation: 7488

Check the array concat function

var obj = {key1:["a","b","c"],key2:["d","e","f"],key3:["g","h"]};

var resultArray = [];
for (var key in obj) resultArray = resultArray.concat(obj[key]);

alert(resultArray);

jsfiddle:

http://jsfiddle.net/qpLq11ea/

Upvotes: 2

Related Questions