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].
Try with Object.values(checkObj).filter(x => x >= 2);
.
Object.values(checkObj)
..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);