var veg = {"mushroom": 30, "pepper": 60, "corn": 1, "carrot":
2, "pumpkin": 4}
If the object value is greater than 5, then print all the keys from veg. I can't seem to figure out how to put the if statement condition within my code.
I got all the values and keys using for loop through the object.
function getKey(veg){
var arr = [];
for (var x of Object.keys(veg)){
arr.push(x);
}
return arr;
}
console.log(getKey(veg))
//----------------------------------------
function getVal(veg){
var arr = [];
for (var i of Object.values(veg)){
arr.push(i);
}
return arr;
}
console.log(getVal(veg))
// END GOAL
must return ["mushroom", "pepper"]
keys() Method: The Object. keys() method is used to return an array whose elements are strings corresponding to the enumerable properties found directly upon an object. The ordering of the properties is the same as that given by the object manually in a loop is applied to the properties.
keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.
Using method for in
var veg = {"mushrooms": 30, "peppers": 60, "meatballs": 1, "chicken":
2, "olives": 4}
function getKey(veg){
const arr = [],
obj = Object.keys(veg);
for (var x in obj){
if(veg[obj[x]] > 5){
arr.push(obj[x]);
}
}
return arr;
}
console.log(getKey(veg))
Using method forEach
var veg = {"mushrooms": 30, "peppers": 60, "meatballs": 1, "chicken":
2, "olives": 4}
function getKey(veg){
const arr = [];
Object.keys(veg).forEach(function(item){
if(veg[item] > 5) arr.push(item);
});
return arr;
}
console.log(getKey(veg));
Using method filter
var veg = {"mushrooms": 30, "peppers": 60, "meatballs": 1, "chicken":
2, "olives": 4}
function filterItems(arr) {
return Object.keys(arr).filter(function(el) {
return arr[el] > 5;
})
}
console.log(filterItems(veg));
var veg = {"mushrooms": 30, "peppers": 60, "meatballs": 1, "chicken":
2, "olives": 4}
function filterItems(arr) {
return Object.keys(arr).filter(el => arr[el] > 5);
}
console.log(filterItems(veg));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With