我有一个这样的对象数组:
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)。
答案 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)