javascript - 如何在对象数组中找到一个值?
问题描述
我有一个这样的对象数组:
var data = [
{id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
{id:2,first_name:'Blaan',last_name:'Adey',age:35,birth:'2001-04-16'}
];
var searchColumn = ['first_name','last_name','birth'];
这些值(searchColumn)可能会改变而不是恒定的。出于这个原因,它们必须从数组中读取
我现在想这样做:
function searchData(Val){
var newData = [];
if (Val){
for (let i=0 ; i < data.length ; i++){
searchColumn.forEach(value => {
if (data[i][value].includes(Val)){
newData.push(data[i]);
}
}
}
}
}
searchData('L');
请指导我。
解决方案
这应该做。
您不必遍历数组,您可以使用内置函数,如map
,some
来filter
实现这一点。
var data = [
{id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
{id:1,first_name:'John',last_name:'Bal',age:20,birth:'1992-01-12'},
{id:2,first_name:'Blaan',last_name:'Adey',age:35,birth:'2001-04-16'}
];
var searchColumn = ['first_name','last_name','birth'];
var search = (searchParam) => {
// map here applies the function (value) => searchColumn.some(property => value[property] === searchParam) ? value : null
// over every value in the array & some loops through every value in the search column
// looking for an object where one of the properties specified in searchColumn has a value that matches our search parameter
return data.map(value => searchColumn.some(property => value[property] === searchParam) ? value : null)
.filter(result => !!result); // here we use filter to remove the null values mapped in the map function
}
search('John');
// result -> [{id:1,first_name:'John',last_name:'Doe',age:20,birth:'1992-01-12'},
// -> {id:1,first_name:'John',last_name:'Bal',age:20,birth:'1992-01-12'}]
更新:正如建议的,一个更好的解决方案:
var search = (searchParam) => {
return data.filter(value => !!searchColumn.some(property => value[property] === searchParam));
}
推荐阅读
- java - 过滤的列表项打开错误的活动
- vb.net - 在Visual Basic中将字符串与字符串列表进行比较
- apache-kafka - Apache 和 Confluent kafka 文档中的 TopicNameMatches 类的包参考错误
- python - 我不明白 python 日志记录模块如何读取其执行代码
- python - 有没有办法从 IEX 获取实时数据?
- php - Woocommerce - 根据某些条件更改添加到购物车按钮文本
- javascript - 通过函数将文件上传到 Firebase 存储
- python - 在python中将秒转换为日期和时间
- c++ - boost::vf2_graph_iso 的实现是单线程的吗?
- javascript - React 应用程序无法识别 require()