javascript - 根据属性返回对象值

标签 javascript arrays javascript-objects

我有一个包含各种动物的对象:

var toonimals = [ {name: 'Itchy', animal: 'mouse'}, {name: 'Stimpy', animal: 'cat'}, {name: 'Daffy', animal: 'duck'}, {name: 'Scratchy', animal: 'cat'}, {name: 'Ren', animal: 'dog'}, {name: 'Felix', animal: 'cat'}]

我只想返回猫类动物的名称。我正在努力这样做。这是我的尝试:

var cats = []
function onlyCats(array) {
  if (toonimals.animal === 'cat') {
    cats.push(toonimals.name)
  }
  return cats
}
console.log(onlyCats(toonimals));

目前,它仅返回空数组,因此 .push() 方法由于某种原因不起作用。

提前谢谢您。

最佳答案

您必须循环数组到 filter()这个动物。然后使用map()修改数组以返回名称:

var toonimals = [ {name: 'Itchy', animal: 'mouse'}, {name: 'Stimpy', animal: 'cat'}, {name: 'Daffy', animal: 'duck'}, {name: 'Scratchy', animal: 'cat'}, {name: 'Ren', animal: 'dog'}, {name: 'Felix', animal: 'cat'}];

function onlyCats(array) {
  return array.filter(a => a.animal === 'cat').map(a => a.name);
}
console.log(onlyCats(toonimals));

forEach()的帮助下以您的方式:

var toonimals = [ {name: 'Itchy', animal: 'mouse'}, {name: 'Stimpy', animal: 'cat'}, {name: 'Daffy', animal: 'duck'}, {name: 'Scratchy', animal: 'cat'}, {name: 'Ren', animal: 'dog'}, {name: 'Felix', animal: 'cat'}];

var cats = []
function onlyCats(array) {
  array.forEach(function(animal){
    if (animal.animal === 'cat') {
      cats.push(animal.name)
    }
  });
  return cats;
}
console.log(onlyCats(toonimals));

关于javascript - 根据属性返回对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54720292/

相关文章:

javascript - 如何修复 javascript 中复制到剪贴板的错误?

javascript - 将列表的 html 和 js 分开

java - Java中的随机数数组 - 想要升序排序

javascript - 计算数组中有多少个具有特定名称的条目并保存以供以后使用

arrays - jq - 如何在 json 中连接数组

javascript - 如何计算对象数组中给定属性的 JavaScript 平均值

javascript - 将此 json 字符串操作为此 javascript 对象

javascript - JQuery 在提交表单后更改表单 url

javascript - 如何在 VSCode 中突出显示全局变量?

javascript - 在这个例子中如何获得父亲的属性(property)呢?