Let’s assume the following JSON structure:
{
"type":"T1",
"velocity":"800",
"speed":"100",
"bulletType":"t1Ammo",
"damagePerHit":"0.25",
"tankWidth":"74",
"tankHeight":"128",
"bulletWidth":"7",
"bulletHeight":"15"
},
{
"type":"T2",
"velocity":"800",
"speed":"100",
"bulletType":"t1Ammo",
"damagePerHit":"0.25"
},
{
"type":"",
"velocity":"",
"speed":"",
"bulletType":"",
"damagePerHit":""
}
]};
In this object we notice how the first object has values that the others do not, if we tried to parse it based on the first object the code would halt on error because it would be unable to find the rest of the keys.
So what if we only wanted one of the objects but we did not know what properties it has?
Let’s consider the following snippet:
function getOptions(type, opts){
var counter = 0;
var obj = {};
for(var i = 0; i<opts.tanks.length; i++){
var temp = opts.tanks[counter];
var keys = Object.keys( temp );
if( temp.type == type){
for(var j=0; j<keys.length; j++){
obj[ keys[ j ] ] = temp[ keys[ j ] ];
}
}
counter += 1;
}
return obj;
}
Here we check if the desired “type” is among the object properties, if it is we read the available “keys” that the object has, and then we construct another object with those keys and values.
Browser compatibility:
This solution is compatible with
Firefox (Gecko) – 4 (2.0)
Chrome – 5
Internet Explorer – 9
Opera – 12
Safari – 5
Because it uses: Object.keys(obj)
Read more here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
