Я разбираю json. Фактически мне нужно найти свойство от json. В моем json у меня есть два вложенных массива (list, array). Мне нужно получить отдельное значение. Но я получаю все значение в массиве, мы можем разделить массив массива "list" в отдельном массиве. "Array" в отдельном массиве. Я получаю это:
33, 44, 23, 11 Вот моя скрипка: http://jsfiddle.net/f5Awq/
var arrayLabel=new Array();
var listLabel=new Array();
function recursiveIteration(object, callback, data) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (typeof object[property] == "object"){
recursiveIteration(object[property], callback, data);
}
else {
callback(object, property, data);
}
}
}
}
function test_cb(object, property, data) { console.log(property);
if(property == data.filter && object[property]){
data.array.push(object[property]);
}
}
recursiveIteration(json, test_cb, {filter: 'label', array: arrayLabel});
console.log(arrayLabel);
document.body.textContent = arrayLabel.join(', ');
Я выхожу в arrayLabel: 33, 44, 23, 11
Мой ожидаемый результат:
arrayLabel: 33, 44. listLabel - 11,23
33, 44 потому что они находятся в "массиве". И 11,23 в списке в моем json.can мы добавим условие?
Я надеюсь, что вы это сделали:
var arrayLabel = {'list':[],'array':[]};
var listLabel = new Array();
function recursiveIteration(object, callback, data,parent) {
parent=parent||'root';
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (typeof object[property] == "object") {
if (['list','array'].indexOf(property)>=0) {parent=property;} //the condion you looked for
recursiveIteration(object[property], callback, data,parent);
} else {
callback(object, property, data,parent);
}
}
}
}
function test_cb(object, property, data,parent) {
if (property == data.filter && object[property]) {
data.array[parent].push(object[property]);
}
}
поэтому я записываю текущее "законное" родительское имя и накапливаю его на данные. Вы можете легко сделать выбор.
listLabel
. почему вы ожидаете, что он станет [11, 23]?