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

2 Answers2

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

Or you directly assign it:

const objArray = Object.values(numObj));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 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 Readwatch Jul 10 '18 at 16:16
  • @needto thats the spread operator. And if you take the second approach, remove the `const objArray = []` – Jonas Wilms Jul 10 '18 at 16:25
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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176