如何访问此对象的键和值?
{
"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"
}]
}
}
}
我尝试了一些技巧,但我不知道自己如何解决这个问题。 这是我的ajax调用,应该管理数据。
$.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);
})
// ...
}
}
});
我希望有人可以帮助我。 关心Sascha
答案 0 :(得分:3)
循环。环。并再循环一次。
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], list = [];
for (var prop in obj2) {
list.push('"' + prop + '": "' + obj2[prop] + '"');
}
log(' Object at index ' + index + '=> ' + list.join(', '));
}
}
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>
答案 1 :(得分:2)
你必须使用三个嵌套循环:
for (const i in data.chat_data.items) {
for (const j of data.chat_data.items[i]) {
for (const key in j) {
const value = j[key]
console.log(key, value)
}
}
}
答案 2 :(得分:0)