最近,我接受了采访,并拒绝了大约10个问题。每个问题都有60
几秒钟。有一个问题出了错,但我很好奇为什么会发生。
我必须过滤那些给定SearchValue
与list
数组对象name
属性匹配的对象。该search
值已经给出。
例如:
const SearchValue = 'event';
它是过滤的数组,因为list[0].name
属性值与event
文本匹配。
const res = [
{
id: 2,
name: 'Events',
list: [
{
id: 1,
name: 'Event Ticketing System',
slug: '/'
},
{
id: 2,
name: 'Events Management Software',
slug: '/'
}
]
}
];
该name
属性包含诸如此类的值Online Translation Services
,Spelling and Grammar Check
等等。如果搜索值与匹配,text
则将那些过滤后的对象和保存到该值console.log
。数据集是这样的。
const listing = [
{
id: 1,
name: 'Language',
list: [
{
id: 1,
name: 'Online Translation Services',
slug: '/'
},
{
id: 2,
name: 'Spelling and Grammar Check',
slug: '/'
},
{
id: 3,
name: 'TEFL Courses',
slug: '/'
},
{
id: 4,
name: 'Language Learning',
slug: '/'
}
]
},
{
id: 2,
name: 'Events',
list: [
{
id: 1,
name: 'Event Ticketing System',
slug: '/'
},
{
id: 2,
name: 'Events Management Software',
slug: '/'
}
]
}
];
我的实现是这样。
const SearchValue = 'event';
const listing = [{
id: 1,
name: 'Language',
list: [{
id: 1,
name: 'Online Translation Services',
slug: '/'
},
{
id: 2,
name: 'Spelling and Grammar Check',
slug: '/'
},
{
id: 3,
name: 'TEFL Courses',
slug: '/'
},
{
id: 4,
name: 'Language Learning',
slug: '/'
}
]
},
{
id: 2,
name: 'Events',
list: [{
id: 1,
name: 'Event Ticketing System',
slug: '/'
},
{
id: 2,
name: 'Events Management Software',
slug: '/'
}
]
}
];
const res = listing.filter(object => {
if (Array.isArray(object.list) && object.list.length > 0) {
return object.list.filter((item) => {
return item.name.toLowerCase().indexOf(SearchValue.toLowerCase()) !== -1;
});
}
});
console.log('Result Array', res);
如果有人能提供一个好的解决方案,我们将不胜感激。我也想知道这个逻辑出了什么问题?
您可以Array#filter
与Array#some
一起使用,以验证list
每个对象的属性的任何元素中是否包含搜索文本name
。
const listing = [ { id: 1, name: 'Language', list: [ { id: 1, name: 'Online Translation Services', slug: '/' }, { id: 2, name: 'Spelling and Grammar Check', slug: '/' }, { id: 3, name: 'TEFL Courses', slug: '/' }, { id: 4, name: 'Language Learning', slug: '/' } ] }, { id: 2, name: 'Events', list: [ { id: 1, name: 'Event Ticketing System', slug: '/' }, { id: 2, name: 'Events Management Software', slug: '/' } ] } ];
const SearchValue = 'event';
const res = listing.filter(({list})=>
list.some(({name})=>name.toLowerCase().includes(SearchValue.toLowerCase())));
console.log(res);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句