【问题标题】:JS filter array of objects by a nested array within object [closed]JS通过对象内的嵌套数组过滤对象数组[关闭]
【发布时间】:2021-07-08 02:15:40
【问题描述】:

我有一个类似的对象数组

 let data = [
      {
        name: 'jake fisher',
        age: 24,
        team_ids: [1234, 5678, 9125],
      },

      {
        name: 'kelly smith',
        age: 46,
        team_ids: [3331, 8884, 1234, 8808, 7621],
      },

      {
        name: 'austin williams',
        age: 66,
        team_ids: [9125, 4445],
      },

      {
        name: 'alex rodriguez',
        age: 27,
        team_ids: [],
      },
    ];

我正在尝试将此对象数组过滤为仅包含 team_ids 编号为 1234 的对象 所以在这个例子中,只有“Jake Fisher”和“Kelly Smith”两个队ID匹配。

我尝试了一些其他解决方案,其中一些让我非常接近,但似乎有一些严重的缺陷。我认为真正让我失望的是它是一个嵌套数组(我正在学习并且我没有经常遇到这个问题!)任何帮助将不胜感激!

【问题讨论】:

  • 查看 Javascript 中的“过滤器”和“包含”方法

标签: javascript arrays reactjs sorting filtering


【解决方案1】:

let data = [{
    name: 'jake fisher',
    age: 24,
    team_ids: [1234, 5678, 9125],
  },

  {
    name: 'kelly smith',
    age: 46,
    team_ids: [3331, 8884, 1234, 8808, 7621],
  },

  {
    name: 'austin williams',
    age: 66,
    team_ids: [9125, 4445],
  },

  {
    name: 'alex rodriguez',
    age: 27,
    team_ids: [],
  },
];

const result = data.filter(item => item.team_ids.indexOf(1234) !== -1)
console.log(result);

【讨论】:

    【解决方案2】:

    let data = [{
        name: 'jake fisher',
        age: 24,
        team_ids: [1234, 5678, 9125],
      },
    
      {
        name: 'kelly smith',
        age: 46,
        team_ids: [3331, 8884, 1234, 8808, 7621],
      },
    
      {
        name: 'austin williams',
        age: 66,
        team_ids: [9125, 4445],
      },
    
      {
        name: 'alex rodriguez',
        age: 27,
        team_ids: [],
      },
    ];
    
    const result = data.filter(item => item.team_ids.includes(1234));
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 2020-03-11
      • 2018-01-16
      • 1970-01-01
      相关资源
      最近更新 更多