JavaScript-制作通用的map/find/filter函数



TLDR您将如何制作一个函数,例如在数组中搜索值,但搜索的属性可能会在哪里更改?

示例。

const search = (arr, text) =>
{
// What if rather than e.name we wanted to search on e.phone?
// And how could this be passed with the function params?
return arr.find(e => e.name === text)
}

您可以使用Array#reduce查找嵌套属性(作为字符串传入(以与文本进行比较。

const search = (arr, prop, text) =>{
const getProp = obj => prop.split('.').reduce((acc,curr)=>acc?.[curr], obj);
return arr.find(e => getProp(e) === text);
}
console.log(search([{a: 1}, {a: {b: 'test'}}], 'a.b', 'test'));
console.log(search([{name: 'Joe'}, {name: 'John'}, {name: 'Bob'}], 'name', 'Bob'));

最新更新