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
asked May 2, 2020 at 11:14
Heisenberg
5,35915 gold badges60 silver badges104 bronze badges
4 Answers 4
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)
answered May 2, 2020 at 11:16
Sebastian Speitel
7,3872 gold badges21 silver badges38 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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)
answered May 2, 2020 at 11:20
Shubham Khatri
284k58 gold badges431 silver badges411 bronze badges
2 Comments
Heisenberg
thank you for answering, sorry for basic questions ,what is the meaning of
... in front of Object? thanksShubham Khatri
That is a spread syntax. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Quick solution is to create an array of obj1 and concat the obj2.
const arr = [obj.obj1].concat(obj.obj2);
answered May 2, 2020 at 11:18
Francesc Montserrat
3491 silver badge8 bronze badges
Comments
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);
answered May 2, 2020 at 11:26
zb22
3,2413 gold badges22 silver badges38 bronze badges
Comments
lang-js