javascript - 如何获取数组中的value属性?

标签 javascript jquery json

我正在使用recusion解析json。我调用我的函数本身。我的json“数组”和“列表”中有两个数组。我需要获取“标签”的属性并保存在数组中。我需要保存值标签位于“列表”和“标签”的单独数组内。我正在尝试这样做,但我的概念受到了影响。如果它来自“数组”(json)的属性,我需要保存在数组中,我需要添加到不同的数组中如果属性来自“列表”。属性是标签。

http://jsfiddle.net/mVz3E/

var arrayLabel=new Array();
var listLabel=new Array();
function recursiveIteration(object, callback) {
    for (var property in object) {
        if (object.hasOwnProperty(property)) {
            if (typeof object[property] == "object"){
                recursiveIteration(object[property], callback);
            }else{
                //found a property which is not an object, check for your conditions here
                callback(object, property);

            }
        }
    }
}

function test_cb(object, property){
    if(property == "label" && object[property]&& object instanceof Array))
    {

        arrayLabel.push(object[property])

    }
}

最佳答案

我确实设法使用您的函数来检索标签,但我不明白 listLabel 数组的样子。

DEMO 已更新

 var json = {...};

 function test_cb(object, property, data) { 
   var array = [];
   if(data.filter(object, property) && object[property]){
     data.array.push(object[property]);
   }
 }

 recursiveIteration(json, test_cb, {
   array: arrayLabel, 
   filter: function(object, property){
          return (property == 'label' && !object.array);
        }
 });
 recursiveIteration(json, test_cb, {
 array: listLabel, 
   filter: function(object, property){
     console.dir(object);
     return (property == 'label' && !!object.list);
   }
 });

 console.log('arrayLabel',arrayLabel);
 console.log('listLabel',arrayLabel);
 document.body.textContent = 'arrayLabel: ' + arrayLabel.join(', ') + 
                      ' - listLabel: ' + listLabel.join(', ');

关于javascript - 如何获取数组中的value属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23832267/

相关文章:

jquery - 选择所有未禁用的输入按钮

javascript - AngularJS 将类应用于事件的父元素?

android - 使用 Retrofit 以这种格式发布字段

javascript - 是否可以在 SVG 中使用 Snap?

javascript - 在html5 Canvas 内制作重力效果

java - 如何根据方法忽略字段?

javascript - d3.js 的日期轴

javascript - Redux 表单 - 您必须将 handleSubmit() 传递给 onSubmit 函数或将 onSubmit 作为 Prop 传递

javascript - 不变违规 : App(. ..) 渲染器未返回任何内容

javascript - 仅在 JS 中定位多个选择器