gpt4 book ai didi

javascript - 如果 key 名称未知,有没有办法访问 json 项目?

转载 作者:行者123 更新时间:2023-12-01 00:40:18 25 4
gpt4 key购买 nike

我想从生成的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com