在数组或类似的上使用jQuery.find()

时间:2012-10-05 14:15:01

标签: javascript jquery

假设我有一个搜索框,其中输入的内容存储为:

var search_input = $(this).val();

如何使用此值搜索我的数组?

var devices = [{"Device_ID":"43","Image":"Amazon-Kindle-Fire.png","Manufacturer":"Amazon","Model":"Kindle Fire","Type":"Tablet"},{"Device_ID":"44","Image":"Apple-iPad.png","Manufacturer":"Apple","Model":"iPad","Type":"Tablet"}]

所以我想在我的search_input变量中使用亚马逊或Kindle等,我希望它能够搜索数组并输出以下内容。这同样适用于任何类型的东西或数组中的任何东西

<div id="device">43</div>
<div id="image">Amazon-Kindle-Fire.png</div>
<div id="name">Amazon Kindle Fire</div>

4 个答案:

答案 0 :(得分:6)

循环中的简单循环

var devices = [{"Device_ID":"43","Image":"Amazon-Kindle-Fire.png","Manufacturer":"Amazon","Model":"Kindle Fire","Type":"Tablet"},{"Device_ID":"44","Image":"Apple-iPad.png","Manufacturer":"Apple","Model":"iPad","Type":"Tablet"}];

function findItem (term) {
    var items = [];
    for (var i=0;i<devices.length;i++) {
        var item = devices[i];
        for (var prop in item) {
            var detail = item[prop].toString().toLowerCase();
            if (detail.indexOf(term)>-1) {
                items.push(item);
                break;               
            }
        }
    }
    return items;
}

console.log( findItem("amazon") );  //returns one item
console.log( findItem("kindle") );  //returns one item
console.log( findItem("apple") );   //returns one item
console.log( findItem("tablet") );  //returns two items
console.log( findItem("nerd") );    //returns zero items
​

jsFiddle

答案 1 :(得分:4)

我认为在这个问题中实现目标的一种更优雅的方法是使用jQuery.grep() - 见http://api.jquery.com/jquery.grep/

var search_input = $(this).val();
var devices = [
       {"Device_ID":"43","Image":"Amazon-Kindle-Fire.png","Manufacturer":"Amazon","Model":"Kindle Fire","Type":"Tablet"},
       {"Device_ID":"44","Image":"Apple-iPad.png","Manufacturer":"Apple","Model":"iPad","Type":"Tablet"}
];

var matchingItems = $.grep(devices, function(e) {
            return (e["Manufacturer"].indexOf(search_input) >- 1 ||
                    e["Model"].indexOf(search_input) > -1);
});

现在matchingItems包含在制造商或模型属性中包含search_input字的项目数组,您可以在html中输出这些内容。

答案 2 :(得分:1)

我认为你需要:

jQuery.inArray()

http://api.jquery.com/jQuery.inArray/

答案 3 :(得分:1)

另一种方法是用地图(JavaScript对象)替换数组,其中键是要与search_input进行比较的值。这样你只需查找键并获得对象。

var devices = {"Amazon Kindle": {"Device_ID":"43","Image":"Amazon-Kindle-Fire.png","Manufacturer":"Amazon","Model":"Kindle Fire","Type":"Tablet"},{"Device_ID":"44","Image":"Apple-iPad.png","Manufacturer":"Apple","Model":"iPad","Type":"Tablet"}}

第二步涉及将JavaScript对象转换为XML,这已在SO What's the best way to serialize JavaScript objects to XML?

上回答了问题。