I'm getting the following JSON response from the server:
[{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"},
{"id":"2","pid":"0","type":"Group","code":"g","status":"1"},
{"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"},
{"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"},
{"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}]
How can I make jQuery foreach loop and get only values of id
and type
.
var json = '[{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"},{"id":"2","pid":"0","type":"Group","code":"g","status":"1"},{"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"},{"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"},{"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}]';
$.each($.parseJSON(json), function() {
alert(this.id + " " + this.type);
});
var json =
[
{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"},
{"id":"2","pid":"0","type":"Group","code":"g","status":"1"},
{"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"},
{"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"},
{"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}
];
$.each(json,function(i,el)
{
alert(el.id+' - '+el.type);
});
Here is that stupid example running
EDIT:
As enoyhs said this could also be achieved with pure javascript which would be a faster solution. Here is a benchmark of looping arrays in javascript vs jQuery:
Working sample here: http://jsfiddle.net/ezmilhouse/emCT8/
Snippet to create new array of objects that only contain id and type keys:
var json = [{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"},{"id":"2","pid":"0","type":"Group","code":"g","status":"1"},{"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"},{"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"},{"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}];
var arr = [];
$.each(json, function(key, value){
arr.push({
id: value.id,
type: value.type
});
});
console.log(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With