Reputation:
How can I do a query to an array javascript, for example I want to find all names that begin with A, an then show all information
Name":"Albert","age":"14"
Name":"Alison","age":"14"
this is my array json:
var house = [{"Name":"Jason","age":"43"},
{"Name":"Albert","age":"14"},
{"Name":"Luck","age":"14"},
{"Name":"Alison","age":"14"},
{"Name":"Tom","age":"12"}]
Upvotes: 1
Views: 365
Reputation: 104760
You can filter an array, to collect the elements with an 'A' name, then forEach or map the matches to a new array of property names and values
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');
/* returned value: (String)*/
Name:Albert,age:14
Name:Alison,age:14
If you need a shim:
(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;
}
}
}
})();
Upvotes: 2
Reputation: 14025
You could also use grep
function
arr = jQuery.grep(house, function (a) { return a.Name.indexOf("A") === 0; });
Upvotes: 1
Reputation: 145388
You can use Array.filter
:
var result = house.filter(function(o) {
return o.Name.indexOf("A") === 0;
});
Some old browsers might not support this method. Check the compatibility and the workaround at MDN.
Upvotes: 5
Reputation: 66304
You can use Array.prototype.filter
var names_beginning_a = house.filter(
function (item) {return item["Name"][0].toLowerCase() === 'a';}
);
Once you have this, you could convert your data to a String using JSON.stringify
and Array.prototype.map
var dataAsString = names_beginning_a.map(
function (item) {return JSON.stringify(item);} // optionally trim off { and }
);
Upvotes: 3