如何通过jquery循环获取内部循环的每个信息的info1或info2的id。例如,我想从info1获取id 1,然后id 1中的所有信息与info2中的相同。我需要输出显示在浏览器中。
var data = {
"info1": {
"1": {
"clientname": "ruhul yahoo",
"clientemail": "ruhul080@yahoo.com",
"clientusername": "ruhulya"
},
"2": {
"clientname": "kaosar yahoo",
"clientemail": "kaosar080@yahoo.com",
"clientusername": "kaosar"
}
},
"info2": {
"3": {
"id": "24",
"receiver": "5",
"content": "chat system",
"time": "2015-08-19 12:09:19"
},
"4": {
"id": "23",
"receiver": "4",
"content": "chat system",
"time": "2015-08-19 12:09:19"
}
},
}

提前致谢。
答案 0 :(得分:1)
迭代json数组并像下面的代码一样访问对象。
var data = {
"info1": {
"1": {
"clientname": "ruhul yahoo",
"clientemail": "ruhul080@yahoo.com",
"clientusername": "ruhulya"
},
"2": {
"clientname": "kaosar yahoo",
"clientemail": "kaosar080@yahoo.com",
"clientusername": "kaosar"
}
},
"info2": {
"3": {
"id": "24",
"receiver": "5",
"content": "chat system",
"time": "2015-08-19 12:09:19"
},
"4": {
"id": "23",
"receiver": "4",
"content": "chat system",
"time": "2015-08-19 12:09:19"
}
},
};
for(var j in data){
for(var k in data[j]){
console.log(data[j][k]);
}
}
如果您运行上面的示例,您的浏览器的控制台将记录以下对象。
Object {clientname: "ruhul yahoo", clientemail: "ruhul080@yahoo.com", clientusername: "ruhulya"}
Object {clientname: "kaosar yahoo", clientemail: "kaosar080@yahoo.com", clientusername: "kaosar"}
Object {id: "24", receiver: "5", content: "chat system", time: "2015-08-19 12:09:19"}
Object {id: "23", receiver: "4", content: "chat system", time: "2015-08-19 12:09:19"}
然后您可以像普通对象console.log(data[j][k].clientname);
答案 1 :(得分:0)
你可以像这样迭代这个对象
for(var i in data){
for(var j in data[i]){
console.log(data[i][j]);
}
}
答案 2 :(得分:0)
此函数将为您找到对象中变量名的第一个实例。如果您需要在特定路径中查找变量,则可以相当容易地修改此函数。当然,该功能通过了您提供的测试用例。
function findVar(data, varName) {
for (var i in data) {
if (i === varName) return data[i];
if (typeof (data[i]) === 'object') {
var findResult = findVar(data[i], varName)
if (typeof(findResult) !== 'undefined')
{
return findResult;
}
}
}
return undefined;
}
答案 3 :(得分:0)
首先,这不是有效的JSON,在最后,
之前移动{
其次,将其解析为JSON并将信息作为
data.info1[1].clientname
var data = JSON.parse('{"info1":{"1":{"clientname":"ruhul yahoo","clientemail":"ruhul080@yahoo.com","clientusername":"ruhulya"},"2":{"clientname":"kaosar yahoo","clientemail":"kaosar080@yahoo.com","clientusername":"kaosar"}},"info2":{"3":{"id":"24","receiver":"5","content":"chat system","time":"2015-08-19 12:09:19"},"4":{"id":"23","receiver":"4","content":"chat system","time":"2015-08-19 12:09:19"}}}');
alert(data.info1[1].clientname);
alert(data.info1[2].clientname);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;