我有这个对象(我不能改变它,它来自外部的web服务),我想得到所有的ID,(数据内部的结构可能会改变)
data: {
consoles:[
{
name:'',
id:''
},
{
name:'',
id:''
}
],
games:[
{
name:'',
id:''
},
{
name:'',
id:''
}
],
accesories:[
{
name:'',
id:''
},
{
name:'',
id:''
}
]
}
我试图用Object.keys(数据)获取对象的所有键,然后尝试打印它
var keys = Object.keys(data);
for(var j = 0; j < keys.length; j++){
console.log(keys[j]);
for(var i = 0; i < data.keys[j].length; i++){
console.log(data.keys[j].id)
}
}
答案 0 :(得分:1)
试试这个: -
var productsKeys = Object.keys(data);
for(var j = 0; j < productsKeys.length; j++){
for(var i = 0; i < data[productsKeys[j]].length; i++){
console.log(data[productsKeys[j]][i].id)
}
}
答案 1 :(得分:1)
尝试将data.keys[j]
替换为:
data[keys[j]]
所以这会给你:
var keys = Object.keys(data);
for(var j = 0; j < keys.length; j++){
console.log(keys[j]);
for(var i = 0; i < data.keys[j].length; i++){
console.log(data[keys[j]].id)
}
}
答案 2 :(得分:0)
这是我的尝试,你怎么能实现这个
data = {
consoles:[
{
name:'',
id:''
},
{
name:'',
id:''
}
],
games:[
{
name:'',
id:''
},
{
name:'',
id:''
}
],
accesories:[
{
name:'',
id:''
},
{
name:'',
id:''
}
]
}
$.each(data,function(key,val){
$.each(data[key],function(k,v){
$.each(v,function(kf,vf){
console.log(kf + "---->" + vf);
});
});
});
答案 3 :(得分:0)
for(var i=0; i<data.consoles.length;i++){
console.log( data.consoles[i].id);
}
for(var i=0; i<data.games.length;i++){
console.log( data.games[i].id);
}
for(var i=0; i<data.accessories.length;i++){
console.log( data.accessories[i].id);
}
如果游戏机,游戏,配件阵列长度相同,我们只能使用一个for
。