首页 > 解决方案 > JavaScript - 制作通用地图/查找/过滤功能

问题描述

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)
    }

标签: javascriptarrays

解决方案


您可以使用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'));


推荐阅读