gpt4 book ai didi

javascript - 使用对象 javascript 在对象数组中搜索

转载 作者:行者123 更新时间:2023-11-30 07:24:11 26 4
gpt4 key购买 nike

我有一个这样的数组

var userdata = [
{"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","status":"Active"},
{"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"},
{"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"},
{"id":4,"gender":"F","first":"Jennifer","last":"Gill","city":"Seattle, WA","status":"Inactive"}
]

我需要在某些条件下过滤这个数组。这些条件的形式是这样的。

var search_object = {gender:"M",city:"Seattle, WA"}
// Gender = M and city = 'Seattle, WA'
var search_object1 = {gender:"M"}
var search_object2 = {city:"Seattle, WA"}
// This is same as above
var search_array = {status:["Active","Inactive"]}
// Status Active or Inactive
var search_array = [{status:"Active"},{status:"Inactive"}]
// Same as above
var search_object1 = {gender:"F"}
var search_array = [{status:"Active"},{status:"Inactive"}]
//Gender = F and status = Active or Inactive
var search_object = {gender:"F"}
var search_array = [{status:["Active","Inactive"]}]
// same as above

我试过循环但失败了。请帮助或建议或提供一些适当的链接以获得帮助。

最佳答案

以下代码涵盖了您提到的所有情况。

function search(searchObj, data) {
if(searchObj instanceof Array) {
return data.reduce(function(prev, current, index, array) {
return prev.concat(search(current, data));
}, []);
} else {
var results = data.filter(function(el) {
for(var prop in searchObj) {
if(searchObj[prop] instanceof Array) {
if(searchObj[prop].indexOf(el[prop]) == -1) {
return false;
}
} else
if(el[prop] !== searchObj[prop]) {
return false;
}
}

return true;
});

return results;
}
};

search(search_object, userdata);

这是 JSFiddle 中的工作示例.

下面是我在上面使用的函数的一些链接:

关于javascript - 使用对象 javascript 在对象数组中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23776217/

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