Heisenberg
Heisenberg

Reputation: 5279

How to create array from object property in javascript

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

Answers (4)

zb22
zb22

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

Shubham Khatri
Shubham Khatri

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

Francesc Montserrat
Francesc Montserrat

Reputation: 349

Quick solution is to create an array of obj1 and concat the obj2.

const arr = [obj.obj1].concat(obj.obj2);

Upvotes: 2

Sebastian Speitel
Sebastian Speitel

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

Related Questions