【问题标题】:Getting names of objects that have and haven't some properties in their arrays获取在其数组中具有和不具有某些属性的对象的名称
【发布时间】:2020-05-20 11:53:22
【问题描述】:

所以我有一个对象数组,其中包含另一个数组,我想获得一个新的对象数组,这些对象的数组中有特定的东西,并排除那些没有的对象。 (在 Javascript 中)

更具体一点。我有一个这样的数组:

let chars = [
  {
    name: 'John',
    abilities: ['swim', 'jump', 'sing']
  },
  {
    name: 'Mark',
    abilities: ['run', 'jump']
  },
  {
    name: 'Bob',
    abilities: ['swim', 'run', 'sing']
  },
  {
    name: 'Jack',
    abilities: ['jump', 'swim', 'run']
  }
];

例如,我只想获得那些会游泳和跳跃但不会跑的角色。

我想过制作两个像

这样的数组
let includeAbilities = ['swim', 'jump'];
let excludeAbilities = ['run'];

然后以某种方式比较它们,但我真的不知道该怎么做。你能帮帮我吗?

【问题讨论】:

  • 欢迎来到 Stack Overflow!请访问help center,使用tour 了解内容和How to Ask。做一些研究,搜索关于 SO 的相关主题;如果您遇到困难,请发布您的尝试minimal reproducible example,并使用[<>] sn-p 编辑器记录输入和预期输出。
  • 感谢您选择我的答案,我实际上简化了一点,使用every() 而不是reduce()。请看一看。
  • @RoboRobok 谢谢,我现在更容易理解了
  • 不客气。如果你愿意,你也可以投票:)

标签: javascript arrays object


【解决方案1】:

我会选择 Array.prototype.filterArray.prototype.every 的完美组合:

const filteredChars = chars.filter(character => (
    includeAbilities.every(
        ability => character.abilities.includes(ability)
    ) &&
    excludeAbilities.every(
        ability => !character.abilities.includes(ability)
    )
));

结果:

[
    {
        name: 'John',
        abilities: ['swim', 'jump', 'sing']
    }
]

在你的例子中唯一匹配的角色是约翰,因为他会游泳和跳跃,但他不会跑。

【讨论】:

    【解决方案2】:

    let chars = [
      {
        name: 'John',
        abilities: ['swim', 'jump', 'sing']
      },
      {
        name: 'Mark',
        abilities: ['run', 'jump']
      },
      {
        name: 'Bob',
        abilities: ['swim', 'run', 'sing']
      },
      {
        name: 'Jack',
        abilities: ['jump', 'swim', 'run']
      }
    ];
    // This is ES6 syntax, arrow functions: char => char.abilities.includes('swim') is the same as  
    // function(char) { return char.abilities.includes('swim') };
    const canSwim = chars.filter(char => char.abilities.includes('swim'));
    console.log(canSwim);
    // You can make it even shorter with destructuring objects
    const canSwimAndSing = chars.filter(({
      abilities
    }) => {
      return abilities.includes('swim') && abilities.includes('sing')
    });
    console.log(canSwimAndSing);

    【讨论】:

      猜你喜欢
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 2021-12-16
      • 2021-12-17
      • 1970-01-01
      • 2018-07-20
      相关资源
      最近更新 更多