3

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

4 Answers 4

7

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

thank you for answering, sorry for basic questions ,what is the meaning of ... in front of Object? thanks
2

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

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.