过滤包含数组的对象数组

时间:2021-04-07 13:25:30

标签: javascript

我有一个这样的对象数组:

const arr = [
  {
    birth_year: '19BBY',
    gender: 'male',
    height: '172',
    name: 'Luke Skywalker',
    titles: [
      'Revenge of the Sith',
      'A New Hope',
      'The Empire Strikes Back',
      'Return of the Jedi',
    ],
  },
  {
    gender: 'n/a',
    height: '167',
    name: 'C-3PO',
    titles: [
      'The Phantom Menace',
      'Attack of the Clones',
      'Revenge of the Sith',
      'A New Hope',
      'The Empire Strikes Back',
      'Return of the Jedi',
    ],
  },
  {
    birth_year: '33BBY',
    gender: 'n/a',
    height: '96',
    name: 'R2-D2',
    titles: [
      'The Phantom Menace',
      'Attack of the Clones',
      'Revenge of the Sith',
      'A New Hope',
      'The Empire Strikes Back',
      'Return of the Jedi',
    ],
  },
];

我想按标题过滤它。例如,如果我按克隆人的攻击

过滤
const test = arr.map(({ titles }) =>
      titles.filter((title) => title === 'Attack of the Clones')
    );

但作为回报,我得到的只有这个:

[[], ['Attack of the Clones'], ['Attack of the Clones']];

而不是在标题数组中包含克隆人的攻击的所有对象(C-3PO、R2-D2)。

2 个答案:

答案 0 :(得分:1)

您可以使用:

arr.filter(el => el.titles.includes('Attack of the Clones'));

或者,使用解构

arr.filter(({titles}) => titles.includes('Attack of the Clones'));

答案 1 :(得分:-1)

一个班轮:

const arr = [
  {
    birth_year: '19BBY',
    gender: 'male',
    height: '172',
    name: 'Luke Skywalker',
    titles: [
      'Revenge of the Sith',
      'A New Hope',
      'The Empire Strikes Back',
      'Return of the Jedi',
    ],
  },
  {
    gender: 'n/a',
    height: '167',
    name: 'C-3PO',
    titles: [
      'The Phantom Menace',
      'Attack of the Clones',
      'Revenge of the Sith',
      'A New Hope',
      'The Empire Strikes Back',
      'Return of the Jedi',
    ],
  },
  {
    birth_year: '33BBY',
    gender: 'n/a',
    height: '96',
    name: 'R2-D2',
    titles: [
      'The Phantom Menace',
      'Attack of the Clones',
      'Revenge of the Sith',
      'A New Hope',
      'The Empire Strikes Back',
      'Return of the Jedi',
    ],
  },
];

const result = arr.map(i => i.titles.find(e => e === 'Attack of the Clones') && i.name).filter(Boolean)
// Or if you want it as a function call:
const getTitle = (title) => arr.map(i => i.titles.find(e => e === title) && i.name).filter(Boolean)
console.log(result, getTitle('Attack of the Clones'))
编辑: 由于您指的是仅获取一个字符串然后获取整个对象(并且我提供了该字符串的解决方案),因此返回整个对象:

const result = arr.map(i => i.titles.find(e => e === 'Attack of the Clones') && i).filter(Boolean)