Iterating with for... in loop in JavaScript

Viewed 387

I have an empty array called objToArray. I'm trying to use a for-in-loop to fill the array with all of the numbers from a hash checkObj object, if the keys have a value greater than or equal to 2.

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

const objToArray = [];

for (let values in checkObj) {
  if (Object.values(checkObj) >=2 ) {
    objToArray.push(checkObj.values())
    }
}

console.log(objToArray);

So far, I get objToArray as an empty array even though it should contain three elements and should equal [2, 5, 18].

6 Answers

Try with Object.values(checkObj).filter(x => x >= 2);.

  1. Get array of all values with Object.values(checkObj).
  2. Filter array and get value >= 2 with .filter(x => x >= 2).

If you want to use for ... in loop then it iterates over key so you can get value with obj[key]. As you have declared for (let values in checkObj) values object will hold key of checkObj. So you can access value with checkObj[values].

Check output below.

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

// Approach 1
let result = Object.values(checkObj).filter(x => x >= 2);
console.log(result);

// Approach 2
const objToArray = [];
for (let values in checkObj) {
  if (checkObj[values] >= 2) {
    objToArray.push(checkObj[values]);
  }
}
console.log(objToArray);

Is this you wanted?

The for...in statement iterates over all enumerable properties of an object that are keyed, it should be key rather than values.

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

const objToArray = [];

for (let key in checkObj) {
  if (checkObj[key] >= 2) {
    objToArray.push(checkObj[key])
  }
}

console.log(objToArray)

Try this:

const checkObj = {
    oddNum: 1,
    evenNum: 2,
    foundNum: 5,
    randomNum: 18
};
    
const objToArray = [];

for (let [key, value] of Object.entries(checkObj)) {
    // console.log(`${key}: ${value}`);
    if(value>=2){
        objToArray.push(value);
    }
}

console.log(objToArray);

Try this

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

let objToArray = [];
objToArray = Object.values(checkObj).filter(elem => elem >= 2);
console.log(objToArray);
const checkObj = {
  oddNum: 1,
  evenNum: 2,
  foundNum: 5,
  randomNum: 18
};

const objToArray = []; 

//changing the loop into a foreach loop that iterates over the keys
Object.keys(checkObj).forEach((key => {
  if (checkObj[key]) {
    objToArray.push(checkObj[key])
  }
}))

try this: I hope you got it ..

let checkObj = {
  oddNum: 1,
  evenNum: 2,
  foundNum: 5,
  randomNum: 18
};

let objToArray = [];

for (let values of Object.values(checkObj)) {
  console.log(values);
  if (values >=2 ) {
    objToArray.push(values)
    }
}
Related