1

How would I fill const objArray with numObj object's values using the Object.values() method? I've only been able to do it with a for loop + push method (demonstrated below)

const numObj = {
  oddNum: 1,
  evenNum: 2,
  foundNum: 5,
  randomNum: 18
};

const objArray = [];

for (var values in numObj) {
  objArray.push(numObj[values]);
  }
1
  • 1
    Object.values() returns the array you want Commented Jul 10, 2018 at 15:59

2 Answers 2

2
 objArray.push(...Object.values(numObj));

Or you directly assign it:

const objArray = Object.values(numObj));
Sign up to request clarification or add additional context in comments.

2 Comments

i've tried directly assigning it with: const objArray = Object.values(numObj)); but it gives me an error says objArray has already been declared. However -- this works! objArray.push(...Object.values(numObj)); what is the "..." because without it, it's an array with in array [[1, 2, 5, 18]]
@needto thats the spread operator. And if you take the second approach, remove the const objArray = []
0

You could use spread syntax with push method.

const numObj = {
  oddNum: 1,
  evenNum: 2,
  foundNum: 5,
  randomNum: 18
};

const objArray = [];
objArray.push(...Object.values(numObj));
console.log(objArray)

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.