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

问题描述 投票:3回答:4
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"]
javascript arrays object key-value-store
4个回答
1
投票

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

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

2
投票

只需使用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);

1
投票

Object.getOwnPropertyNames将返回一个对象属性的数组,filter返回一个数组,其中传递给input函数的数组中的项返回true,在这种情况下大于5。

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

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

1
投票

您应该使用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);
© www.soinside.com 2019 - 2024. All rights reserved.