Search code examples
javascriptfor-in-loop

Iterating with for... in loop in JavaScript


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].


Solution

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