Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output the object keys when the condition for object values is greater than 5

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"]
like image 665
swiftly Avatar asked Apr 13 '19 00:04

swiftly


People also ask

What is object keys method?

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.

How do you find the number of keys in an object?

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.


1 Answers

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));
like image 144
Юрий Светлов Avatar answered Nov 14 '22 23:11

Юрий Светлов