Как мне перебрать структуру JSON? [Дубликат]

Это прекрасно работает ....

int a = nextInt(); int b = nextInt(); int c = nextInt();

Или вы можете прочитать их в цикле

475
задан John 31 May 2019 в 21:08
поделиться

4 ответа

Взято из jQuery docs :

var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };

jQuery.each(arr, function() {
  $("#" + this).text("My id is " + this + ".");
  return (this != "four"); // will stop running to skip "five"
});

jQuery.each(obj, function(i, val) {
  $("#" + i).append(document.createTextNode(" - " + val));
});
430
ответ дан 22 November 2019 в 22:43
поделиться

Пример mootools:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});
16
ответ дан 22 November 2019 в 22:43
поделиться

Вы можете использовать мини-библиотеку, например objx - http://objx.googlecode.com/

Вы можете написать такой код:

var data =  [ {"id":"10", "class": "child-of-9"},
              {"id":"11", "class": "child-of-10"}];

// alert all IDs
objx(data).each(function(item) { alert(item.id) });

// get all IDs into a new array
var ids = objx(data).collect("id").obj();

// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()

Есть еще 'плагины 'доступны, чтобы вы могли обрабатывать подобные данные, см. http://code.google.com/p/objx-plugins/wiki/PluginLibrary

10
ответ дан 22 November 2019 в 22:43
поделиться
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];

for (var i = 0; i < arr.length; i++){
    var obj = arr[i];
    for (var key in obj){
        var attrName = key;
        var attrValue = obj[key];
    }
}

var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}]; for (var i = 0; i < arr.length; i++){ document.write("

array index: " + i); var obj = arr[i]; for (var key in obj){ var value = obj[key]; document.write("
- " + key + ": " + value); } }

note: the for-in method is cool for simple objects. Not very smart to use with DOM object.

495
ответ дан 22 November 2019 в 22:43
поделиться
Другие вопросы по тегам:

Похожие вопросы: