简体   繁体   中英

Testing for existence of a properties in JSON using javascript

I have the following JSON ("name" has more members only showing "cinema" here for simplicity)

{
    "name": {
        "cinema": {
            "size": {
                "w": 256,
                "h": 200
            },
            "frame": {
                "x": 0,
                "y": 0,
                "w": 256,
                "h": 200
            }
        }
     }
}

Which has been parsed using JSON.parse and stored in the varable bts_json . I want to loop through each member of "name" and detect if it has the member "frame". Below is my code, I get nothing printed on the console.

buildingNames = bts_json.name;

for (buildingFrame in buildingNames) {
   if (buildingFrame.hasOwnProperty("frame")) {
          console.log('exists');
          console.log(buildingFrame["frame"]["y"]);
    }
}

Where am I going wrong?

Thanks for helping :)

You won't get the object , but the property name in buildingFrame , so you need to make it work like

if (buildingNames[ buildingFrame ].hasOwnProperty("frame")) {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM