1

如何对数组 javascript 进行查询,例如我想查找所有以 A 开头的名称,然后显示所有信息

姓名":"阿尔伯特","年龄":"14"
姓名":"艾莉森","年龄":"14"

这是我的数组 json:

var house = [{"Name":"Jason","age":"43"},
{"Name":"Albert","age":"14"},
{"Name":"Luck","age":"14"},
{"Name":"Alison","age":"14"},
{"Name":"Tom","age":"12"}]
4

4 回答 4

5

您可以使用Array.filter

var result = house.filter(function(o) {
    return o.Name.indexOf("A") === 0;
});

一些旧的浏览器可能不支持这种方法。在MDN检查兼容性和解决方法

于 2013-01-27T16:45:02.277 回答
3

您可以使用Array.prototype.filter

var names_beginning_a = house.filter(
    function (item) {return item["Name"][0].toLowerCase() === 'a';}
);

一旦你有了这个,你可以使用和将你的数据转换为字符串JSON.stringifyArray.prototype.map

var dataAsString = names_beginning_a.map(
    function (item) {return JSON.stringify(item);} // optionally trim off { and }
);
于 2013-01-27T16:44:59.347 回答
2

您可以过滤数组,以收集具有“A”名称的元素,然后 forEach 或将匹配项映射到新的属性名称和值数组

house.filter(function(itm){
    return itm.Name.charAt(0)== 'A';
}).map(function(o){
    var A= [];
    for(var p in o){
        if(o.hasOwnProperty(p)){
            A.push(p+':'+o[p]);
        }
    }
    return A;
}).join('\n');

/* 返回值:(字符串)*/

Name:Albert,age:14
Name:Alison,age:14

如果您需要垫片:

(function(){
    var A= Array.prototype;
    if(!A.filter)   A.filter= function(fun, scope){
        var T= this, A= [], i= 0, itm, L= T.length;
        if(typeof fun== 'function'){
            while(i<L){
                if(i in T){
                    itm= T[i];
                    if(fun.call(scope, itm, i, T)) A[A.length]= itm;
                }
                ++i;
            }
        }
        return A;
    }
    if(!A.map) A.map= function(fun, scope){
        var T= this, L= T.length, A= Array(L), i= 0;
        if(typeof fun== 'function'){
            while(i<L){
                if(i in T){
                    A[i]= fun.call(scope, T[i], i, T);
                }
                ++i;
            }
            return A;
        }
    }
}
})();
于 2013-01-27T16:52:39.947 回答
1

你也可以使用grep函数

arr = jQuery.grep(house, function (a) { return a.Name.indexOf("A") === 0; });

http://jsfiddle.net/vYZBb/

于 2013-01-27T16:49:04.767 回答