Sascha Heim Sascha Heim - 6 months ago 56
Javascript Question

Handle multidimensional json array

How can I access the key and values of this object?

{
"chat_data": {
"nickname": "somevalue",
"items": {
"FncZ9Q": [{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
}, {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
}, {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
}],
"GYDjsA": [{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
}, {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
}]
}
}
}


I tried some techniques but I don't know how I solve this issue by myself.
Here is my ajax call where the data should be managed.

$.ajax({
url: "/dataUrl",
type: "post",
cache: false,
dataType: 'json',
success: function (data) {
for (var key in data.chat_data.items) {
var obj = data.chat_data.items[key];
$.each(data.chat_data.items, function (i, value) {
console.log('Value of ' + i + ' is : ' + value);
})
// ...
}
}
});


I hope someone can help me out.
Regards Sascha

Answer

Loop. Loop. And loop one more time.

var data = JSON.parse('{"chat_data":{"nickname":"somevalue","items":{"FncZ9Q":[{"key1":"value1","key2":"value2","key3":"value3","key4":"value4","key5":"value5"},{"key1":"value1","key2":"value2","key3":"value3","key4":"value4","key5":"value5"},{"key1":"value1","key2":"value2","key3":"value3","key4":"value4","key5":"value5"}],"GYDjsA":[{"key1":"value1","key2":"value2","key3":"value3","key4":"value4","key5":"value5"},{"key1":"value1","key2":"value2","key3":"value3","key4":"value4","key5":"value5"}]}}}');

for (var key in data.chat_data.items) {
    var obj = data.chat_data.items[key];
    log('Item "' + key + '":');
    for (var index in obj) {
        var obj2 = obj[index];
        log('    Object at index ' + index + ':"');
        for (var prop in obj2) {
            log('        Property: "' + prop + '", Key: "' + obj2[prop] + '"');
        }
    }
}

function log(txt){ document.body.innerHTML += '<pre>' + txt + '</pre>'; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>