gpt4 book ai didi

javascript - 根据所有属性值过滤对象数组

转载 作者:数据小太阳 更新时间:2023-10-29 06:00:28 24 4
gpt4 key购买 nike

我真的很惊讶我找不到与我的问题相关的任何内容。我正在寻找一种基于用户文本输入来过滤我的对象数组的快速方法。

假设我有这个数组:

let data = [{
"id": 1,
"first_name": "Jean",
"last_name": "Owens",
"email": "jowens0@google.ru",
"gender": "Female"
}, {
"id": 2,
"first_name": "Marie",
"last_name": "Morris",
"email": "mmorris1@engadget.com",
"gender": "Female"
}, {
"id": 3,
"first_name": "Larry",
"last_name": "Wallace",
"email": "lwallace2@example.com",
"gender": "Male"
}];

用户输入“s”,预期结果为:

let result = [{
"id": 1,
"first_name": "Jean",
"last_name": "Owens",
"email": "jowens0@google.ru",
"gender": "Female"
}, {
"id": 2,
"first_name": "Marie",
"last_name": "Morris",
"email": "mmorris1@engadget.com",
"gender": "Female"
}]

我可以这样使用过滤函数:

let = searchText = "s";
let result = data.filter(object=>{
for (var property in object) {
if (object.hasOwnProperty(property)) {
return object[property].toString().toLowerCase().indexOf(searchText) !== -1;
}
}
});

所以我想知道这个解决方案是否有更好的替代方案?

--这是一个有效的JsFiddle感谢 KoolShams

-- Plunker用于基准测试(使用 2k 数据进行测试)

最佳答案

您可以改用 Object.keys()some()

let data = [{
"id": 1,
"first_name": "Jean",
"last_name": "Owens",
"email": "jowens0@google.ru",
"gender": "Female"
}, {
"id": 2,
"first_name": "Marie",
"last_name": "Morris",
"email": "mmorris1@engadget.com",
"gender": "Female"
}, {
"id": 3,
"first_name": "Larry",
"last_name": "Wallace",
"email": "lwallace2@example.com",
"gender": "Male"
}];

var result = data.filter(function(o) {
return Object.keys(o).some(function(k) {
return o[k].toString().toLowerCase().indexOf('s') != -1;
})
})

console.log(result)

关于javascript - 根据所有属性值过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com