如何动态循环getJson数据结果

时间:2018-05-13 07:51:30

标签: javascript jquery json

我使用jQuery $ .getJSON从API中获取数据,返回多个级别的json数据。级别之一是动态的,我想使用varible来访问它。以下是结果示例:

{
    "status" : "200",
    "result" : {
        "DYNAMIC_DATA_1" : {
            "name" : "Johny",
            "age" : "20"
        },
        "DYNAMIC_DATA_2" : {
            "name" : "Jenny",
            "age" : "25"
        }
    }
}

从上面的示例中,“DYNAMIC_DATA_1”和“DYNAMIC_DATA_2”实际上是一个唯一的ID。

这是我的代码,用于请求json数据:

$(function(){
    $.getJSON('/api/username?id='+DYNAMIC_USER_ID, function(data) {
        console.log(data.result.DYNAMIC_DATA.name);
    });
});

我想动态循环data.result.the-id/key以获取每个name值。

2 个答案:

答案 0 :(得分:2)

使用简单的循环,您可以遍历 data.result ,无论其实际的密钥名称,还是您的唯一ID ,这里有一些解决方案您可以在getJSON函数中使用,例如

$(function(){
    $.getJSON('/api/username?id='+DYNAMIC_USER_ID, function(data) {
        $.each( data.result, function( key, value ) {
            console.log("Name:", value.name, "(ID/Key is " + key + ")");
        });    
    });
});

Stack snippet

var data = {
    "status" : "200",
    "result" : {
        "DYNAMIC_DATA_1" : {
            "name" : "Johny",
            "age" : "20"
        },
        "OTHER_DYNAMIC_DATA_WORKS_TOO" : {
            "name" : "Jenny",
            "age" : "25"
        }
    }
}

//jQuery each
console.log("jQuery each");
$.each( data.result, function( key, value ) {
    console.log("Name:", value.name, "(ID/Key is " + key + ")");
});

//js for-in
console.log("js for-in");
for (var key in data.result) {
    console.log("Name:", data.result[key].name, "(ID/Key is " + key + ")");
}

//js forEach
console.log("js forEach");
Object.keys(data.result).forEach(function(key) {
    console.log("Name:", data.result[key].name, "(ID/Key is " + key + ")");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

直接尝试

&#13;
&#13;
let loggedData = JSON.parse(localStorage.getItem('loggedInfo'));
//Convert String to Object and Local Storage data
&#13;
&#13;
&#13;