如何使用对象的键返回过滤的对象数组



我想写一个函数,它接受两个参数(一个对象数组和一个搜索字符串(。函数应返回一个数组,该数组已按其各自的键过滤了每个对象数组。

我的样本数组和搜索字符串看起来像这个

const myArray = [{
createdAt: 1579147513645,
updatedAt: 1579147513645,
id: 3,
course: "Test",
techStack: "Test ",
…
} {
createdAt: 1581047008746,
updatedAt: 1581047008746,
id: 4,
course: "COmputer Science and mathemetics",
techStack: "Javascript and python, css and html",
…
} {
createdAt: 1582538141524,
updatedAt: 1582538141524,
id: 5,
course: "trrrt",
techStack: "dddf",
…
}]
const searchString = "sc"

我想要一个函数,如果任何对象键(当然是它、techStack或其他键(包含字母"sc",则在数组中返回对象。

只是为了支持我的观点。我将展示一个函数,它执行类似的操作,但只处理"课程"对象键。

const filterResult = (array, query) => {
const filterCriteria = el => el.course.toLowerCase().indexOf(query.toLowerCase()) !== -1;
return array.filter(filterCriteria)
};

使用Object.values()获取对象中所有值的数组,然后使用Array.prototype.some()检查是否有任何值包含搜索字符串。

const filterResult = (array, query) => {
query = query.toLowerCase();
const filterCriteria = el => Object.values(el).some(prop =>
typeof prop == 'string' &&
prop.toLowerCase().includes(query));
return array.filter(filterCriteria)
};
const myArray = [{
createdAt: 1579147513645,
updatedAt: 1579147513645,
id: 3,
course: "Test",
techStack: "Test ",
}, {
createdAt: 1581047008746,
updatedAt: 1581047008746,
id: 4,
course: "COmputer Science and mathemetics",
techStack: "Javascript and python, css and html",
}, {
createdAt: 1582538141524,
updatedAt: 1582538141524,
id: 5,
course: "trrrt",
techStack: "dddf",
}]
const searchString = "sc"
console.log(filterResult(myArray, searchString));

你可以试试这个:

function toSearchableString(str) {
return str ? str.trim().toLowerCase() : '';
}
const filterByTerm = (item, searchString) => toSearchableString(item).includes(toSearchableString(searchString));
const filterData = (dataArray, searchString) => {
const result = dataArray.filter(data => {
const course = data.course ? filterByTerm(data.course, searchString) : false;
const techStack = data.techStack ? filterByTerm(data.techStack, searchString) : false;
// ... include here all object keys you want to be filtered based on searchString
return course || techStack;
});
return result;
};

最新更新