Reputation: 13
I want to access json items from generated keys (generated in php and encoded to json). Is it possible to increment a variable to access it?
Here is my generated JSON (sorry it looks weird in here):
{
"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
}
}
I tried to (poorly) do it with simple tricks but it doesn't work. Is there a way?
Here is my code:
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");
}
}
I'd like to access "buildings.build1.object_type" but "build1" should somehow increment.
Upvotes: 0
Views: 74
Reputation: 13
You can iterate over keys of object:
Object.keys(yourJsonObject).forEach(key => console.log(`${key}: ${yourJsonObject[key]}`));
or you can access value by key declined in string:
const myKey = "build2";
console.log(yourJsonObject[mykey]);
// Should log:
// {
// "object_id":11,
// "object_type":"house",
// "object_x":631,
// "object_y":101
// }
Upvotes: 0
Reputation: 8558
You can use Object.values()
to get values of the object as an array. And then iterate over it:
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;
}
}
Upvotes: 2