javascript - 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)
}
解决方案
您可以使用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'));
推荐阅读
- python - 条件 Django 表单验证
- regex - 使用正则表达式从具有已知前缀的字符串中提取多个单词
- javascript - 在javascript中转换为e+的脚本
- qt - 基于 CMake 的项目,在运行时加载了自定义 QML 插件,仅使用 MinGW 失败
- snakemake - Snakemake 中的 CalledProcessError
- json - 通过 json 的 jquery 循环无法按预期工作
- mysql - SQL 可以单独插入,但不能作为带有外键的文件加载
- azure - 在混合节点池(Windows/Linux)上的 AKS 上忽略 nodeSelector 约束?
- spring-boot - MissingServletRequestParameterException 未使用 @ControllerAdvice 捕获
- apache-spark - spark nlp中的多语言bert