开发者

Check the Key of JSON

var x = {
    "completed": "",
    "globalExposures": "10",
    "tagExposures": [
        {"8": 11},{"5": 12},{"10":23}      
    ]
};

I want to access the Keys of "tagExposures" i.e. 8, 5 and 10 using JSON. I want to perform operation if specific key is present. I tried below code, but it doesn't give desired o/p. Please, Suggest.

var exp = {
    "completed": "",
    "globalExposures": "10",
    "tagExposures": [
        {"8": 11},{"5": 12} ,{"10":23}      
    ]
};
var arr=exp["tagExposures"];
var kys开发者_开发百科=[];
for(k in arr){
  if(arr.hasOwnProperty(k)) kys.push(k);
}
console.log(kys); //=> This gives ['0','1']


That is because tagExposures is an array with keys 0 and 1

"tagExposures": [
        {"8": 11},// 0
        {"5": 12} // 1      
    ]

If you try your same code with tagExposures looking like this:

"tagExposures": {
        "8": 11,
        "5": 12      
    }

It would work as you wanted.

Fiddle: http://jsfiddle.net/maniator/H5z6N/

Output: ["5", "8"]


I think you have misdefined the tagExposures associative array. This gives "8, 5" for example:

var exp = {
    "completed": "",
    "globalExposures": "10",
    "tagExposures": {
        "8": 11,"5": 12
    }
};
var arr=exp["tagExposures"];
var kys=[];
for(k in arr){
  if(arr.hasOwnProperty(k)) kys.push(k);
}
console.log(kys);


for(k in arr){
  if(arr.hasOwnProperty(k)) kys.push(k);
}

is wrong for arrays. Just use a normal loop in combination with Object.keys, which returns the keys of each object (which is one key each time):

for(var i = 0; i < arr.length; i++){
    kys = kys.concat(Object.keys(arr[i]));
}


Your for(k in arr) loop is giving you the keys from tagExposures, which is an array. You need another for loop to get the keys from the objects.

for(k in arr){
    if(arr.hasOwnProperty(k)){
        var obj = arr[k];
        for(v in obj){
            if(obj.hasOwnProperty(v)){
                kys.push(v);
            }
        }
    }
}
console.log(kys); // ["8", "5", "10"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜