JS搜索对象值 [英] JS search in object values
问题描述
我有一系列同类对象,如此;
I have an array of homogeneous objects like so;
[
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
]
我想用关键字搜索这些对象的值(而不是键),并返回包含任何值中的关键字。
I'd like to search these objects' values (not keys) with a keyword, and return an array of objects that contain the keyword in any of the values.
例如,使用关键字 r
,我会获得所有对象(对象#1中的baR,对象#2中的loRem和对象#3中的doloR)。使用关键字 lo
,我会得到对象2和3(LOrem和doLOr), a
,我得到对象1和3,(bAr和Amet)。但是,使用关键字 foo
,我会得到一个空数组,因为foo是一个键,并且在任何值中都找不到(与bar不同) ......你明白了。
So for example, with a keyword r
, I would get all the objects ("baR" in object #1, "loRem" in object #2 and "doloR" in object #3). With a keyword lo
, I would get objects 2 and 3 ("LOrem" and "doLOr"), with a
, I'd get objects 1 and 3, ("bAr" and "Amet"). With the keyword foo
however, I would get an empty array, since "foo" is a key, and isn't found in any of the values (unlike "bar")... you get the idea.
我将如何做到这一点?非常感谢提前!
How would I go about doing this? Thanks a lot in advance!
推荐答案
这样的事情:
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
];
var results = [];
var toSearch = "lo";
for(var i=0; i<objects.length; i++) {
for(key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
results.push(objects[i]);
}
}
}
结果数组将包含所有匹配的对象。
The results array will contain all matched objects.
如果搜索'lo',结果将如下:
If you search for 'lo', the result will be like:
[{ foo="lorem", bar="ipsum"}, { foo="dolor", bar="amet"}]
新版本 - 添加修剪代码,代码以确保结果集中没有重复。
function trimString(s) {
var l=0, r=s.length -1;
while(l < s.length && s[l] == ' ') l++;
while(r > l && s[r] == ' ') r-=1;
return s.substring(l, r+1);
}
function compareObjects(o1, o2) {
var k = '';
for(k in o1) if(o1[k] != o2[k]) return false;
for(k in o2) if(o1[k] != o2[k]) return false;
return true;
}
function itemExists(haystack, needle) {
for(var i=0; i<haystack.length; i++) if(compareObjects(haystack[i], needle)) return true;
return false;
}
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor blor",
"bar" : "amet blo"
}
];
function searchFor(toSearch) {
var results = [];
toSearch = trimString(toSearch); // trim it
for(var i=0; i<objects.length; i++) {
for(var key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
if(!itemExists(results, objects[i])) results.push(objects[i]);
}
}
}
return results;
}
console.log(searchFor('lo '));
这篇关于JS搜索对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!