首页 > 解决方案 > 在另一个对象数组中过滤对象数组

问题描述

我有以下array对象

[
  {
    weakness: [
      "Fire",
      "Flying",
      "Ice",
      "Psychic"
    ],
    id: 1,
    type: [
      "grass",
      "poison"
    ]
  },
  {
    weight: 28.7,
    weakness: [
      "Fire",
      "Flying",
      "Ice",
      "Psychic"
    ],
    id: 2,
    type: [
      "grass",
      "poison"
    ]
  },
  {
    weakness: [
      "Fire",
      "Psychic",
      "Flying",
      "Ice"
    ],
    id: 3,
    type: [
      "grass",
      "poison"
    ]
  },
  {
    weakness: [
      "Fire",
      "Flying",
      "Ice",
      "Psychic"
    ],
    id: 3,
    type: [
      "grass",
      "poison"
    ]
  }
]

我想根据类型过滤,例如“草”类型

但是,我无法输入array进行此操作

我尝试使用过滤器进行过滤,但没有成功

标签: javascriptarraysreactjs

解决方案


有一个包含 4 个对象的数组,最后一个没有草。您可以使用此过滤器获得输出。

let a = [
  {
    weakness: [
      "Fire",
      "Flying",
      "Ice",
      "Psychic"
    ],
    id: 1,
    type: [
      "grass",
      "poison"
    ]
  },
  {
    weight: 28.7,
    weakness: [
      "Fire",
      "Flying",
      "Ice",
      "Psychic"
    ],
    id: 2,
    type: [
      "grass",
      "poison"
    ]
  },
  {
    weakness: [
      "Fire",
      "Psychic",
      "Flying",
      "Ice"
    ],
    id: 3,
    type: [
      "grass",
      "poison"
    ]
  },
  {
    weakness: [
      "Fire",
      "Flying",
      "Ice",
      "Psychic"
    ],
    id: 4,
    type: [
      "poison"
    ]
  }
]

console.log(a.filter(e => e.type.findIndex(e => e === 'grass') > -1))


推荐阅读