作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想从生成的 key (在 php 中生成并编码为 json)访问 json 项。是否可以增加变量来访问它?
这是我生成的 JSON(抱歉,这里看起来很奇怪):
{
"build1":{
"object_id":1,
"object_type":"school",
"object_x":628,
"object_y":131
},
"build2":{
"object_id":11,
"object_type":"house",
"object_x":631,
"object_y":101
},
"build3":{
"object_id":12,
"object_type":"school",
"object_x":498,
"object_y":131
},
"build4":{
"object_id":13,
"object_type":"house",
"object_x":770,
"object_y":154
},
"build5": {"object_id":14,
"object_type":"house",
"object_x":526,
"object_y":217
},
"build6":{
"object_id":15,
"object_type":"house",
"object_x":563,
"object_y":264
}
}
我尝试(糟糕地)用简单的技巧来做到这一点,但它不起作用。有办法吗?
这是我的代码:
for(var i=1; i<= buildingsLength; i++){
var build= "build"+i;
var buildaccess= "buildings"+"."+build;
var buildType= buildaccess+"."+"object_type";
if (buildType === "house"){
console.log("yes, its a house");
var img = new Image();
img.src = "../img/house.png";
img.onload = function(){
ctx.drawImage(img,100,100);
};
}else if (buildType === "school") {
console.log("yes, its a school");
var img = new Image();
img.src = "../img/school.png";
img.onload = function(){
ctx.drawImage(img,100,100);
};
}else{
console.log("error");
}
}
我想访问“buildings.build1.object_type”,但“build1”应该以某种方式递增。
最佳答案
您可以使用Object.values()
以数组形式获取对象的值。然后迭代它:
const myJson = {
"build1":{
"object_id":1,
"object_type":"school",
"object_x":628,
"object_y":131
},
"build2":{
"object_id":11,
"object_type":"house",
"object_x":631,
"object_y":101
},
"build3":{
"object_id":12,
"object_type":"school",
"object_x":498,
"object_y":131
},
"build4":{
"object_id":13,
"object_type":"house",
"object_x":770,
"object_y":154
},
"build5": {"object_id":14,
"object_type":"house",
"object_x":526,
"object_y":217
},
"build6":{
"object_id":15,
"object_type":"house",
"object_x":563,
"object_y":264
}
};
for(let build of Object.values(myJson)){
switch(build.object_type){
case 'house':{
console.log("It's a house!");
break;
}
case 'school':{
console.log("It's a school!");
break;
}
default: break;
}
}
关于javascript - 如果 key 名称未知,有没有办法访问 json 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57768773/
我是一名优秀的程序员,十分优秀!