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

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)

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)

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);

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);

Comments

Your Answer

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.