【问题标题】:Get values by key in the Array of object在对象数组中按键获取值
【发布时间】:2022-11-17 17:08:18
【问题描述】:

我有一个数组,其中包含包含各种键和值的对象。我将从数组中挑选出某些值,并检查数组中是否包含特定值。

function groupByName (contract) {
 const { age } = contract;

 const groups = [
  {name: 'John', age: 30},
  {name: 'Jack', age: 33},
  {name: 'Tom', age: 40}
  ...
 ];
 ...
}

为了比较groups数组中的age,现在我必须使用循环函数,然后一一检查。 喜欢

groups.forEach(g => {
 if (g.age === age) {
  ...
 } else {
  ...
 }
});

但我不喜欢这种方法,认为有简单有效的方法。 请帮我!

【问题讨论】:

  • groups.filter(g => g.age == age)试试这个
  • @lucumt:代码中有一个if/else,所以你的建议不一定有帮助。这实际上取决于 if/else 中的内容(更具体地说,'else' 部分中的内容,因为您的过滤器基本上会跳过该部分中处理的每个元素)。当问题要求“简单有效的方法”时,这个问题通常不会提供太多信息,因为问题是 - 一种简单有效的方法来做什么?

标签: javascript


【解决方案1】:

您可以使用filter 创建两个子列表

像这样

const groups = [
  {name: 'John', age: 30},
  {name: 'Jack', age: 33},
  {name: 'Tom', age: 40}
  ]
  
const withAge = age => groups.filter(g => g.age === age)
const withoutAge = age => groups.filter(g => g.age !== age)

const age30 = withAge(30)

const ageNot30 = withoutAge(30)

age30.forEach(g => {
  console.log('do some stuff with age 30', g)
})

ageNot30.forEach(g => {
  console.log('do some stuff without age 30', g)
})

【讨论】:

    【解决方案2】:

    也许你可以看到这个功能

    groups.some(p=>r.age===age)//if there is a object meet the criteria, return true, else return false
    

    或阅读此https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

    顺便说一句,如果你想在循环中执行 if/else sn-p,也许你应该使用 forEach

    【讨论】:

      【解决方案3】:

      您可以使用.find() 方法来获得准确的结果

      groups.find( group => group.age === age);
      

      这是一个完整的代码

      function groupByName(contract) {
        const { age } = contract;
      
        const groups = [
          { name: 'John', age: 30 },
          { name: 'Jack', age: 33 },
          { name: 'Tom', age: 40 },
        ];
      
        return groups.find((group) => group.age === age); // Returns the result
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多