Reputation: 5279
I would like to get result like
arr=['A','B','C','D']
from the object like below.
var obj = {
obj1: 'A',
obj2: [ 'B', 'C', 'D' ] }
How to reach out to concatenate to array?
If someone has opinion, please let me know.
Thanks
Upvotes: 3
Views: 78
Reputation: 3231
You can use reduce()
followed by Object.values()
var obj = {
obj1: 'A',
obj2: [ 'B', 'C', 'D' ]
};
const res = Object.values(obj).reduce((acc, curr) => [...acc, ...curr], []);
console.log(res);
Upvotes: 1
Reputation: 281646
You can make use of Object.values
and spread it into a single array with Array.prototype.concat
since Array.prototype.flat
is not supported in older browsers
var obj = {
obj1: 'A',
obj2: ['B', 'C', 'D']
}
var vals = [].concat(...Object.values(obj))
console.log(vals)
Upvotes: 3
Reputation: 349
Quick solution is to create an array of obj1 and concat the obj2.
const arr = [obj.obj1].concat(obj.obj2);
Upvotes: 2
Reputation: 7336
You can get the values using Object.values()
and to get them in one array you can use Array.prototype.flat()
:
var obj = {
obj1: 'A',
obj2: ['B', 'C', 'D']
}
var arr = Object.values(obj).flat()
console.log(arr)
Upvotes: 7