当对象值的条件大于 5 时输出对象键

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}

如果对象值大于5,则打印veg中的所有键。我似乎无法弄清楚如何将 if 语句条件放入我的代码中。

我使用 for 循环遍历对象获得了所有的值和键。

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

中使用方法

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

使用方法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));

使用方法过滤器

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

Object.getOwnPropertyNames 将 return 对象的属性数组,过滤 returns 数组,其中数组中的项目传递到输入函数 return是的,在本例中大于 5。

var veg = {"mushroom": 30, "pepper": 60, "corn": 1, "carrot": 2, "pumpkin": 4};

console.log(Object.getOwnPropertyNames(veg).filter(prop => veg[prop] > 5));

您应该使用 for-in 循环遍历对象:

const veg = {"mushroom": 30, "pepper": 60, "corn": 1, "carrot": 2, "pumpkin": 4};

const out = [];

for (let key in veg) {
  if (veg[key] > 5) out.push(key);
}

console.log(out);

只需将 filtermapObject.entries 一起使用:

var veg = {
  "mushroom": 30,
  "pepper": 60,
  "corn": 1,
  "carrot": 2,
  "pumpkin": 4
};
var keys = Object.entries(veg).filter(([, v]) => v > 5).map(([k]) => k);
console.log(keys);