Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json values in jQuery foreach loop

Tags:

json

jquery

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.

like image 774
Simpanoz Avatar asked Apr 21 '11 12:04

Simpanoz


3 Answers

    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);
    });
like image 83
Sotomajor Avatar answered Nov 15 '22 06:11

Sotomajor


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:

like image 24
Dalen Avatar answered Nov 15 '22 07:11

Dalen


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);
like image 20
ezmilhouse Avatar answered Nov 15 '22 06:11

ezmilhouse