Remove ''
as yours is not a valid string, remove ''
to make it a valid object literal, then you can iterate over the keys of the Object and check if it has the matching POSTCODE and if it has then return it's corresponding state.
var data = {
"1": {
"state": "VIC",
"postcode": "2600,2603,2605,2606"
},
"2": {
"state": "NSW",
"postcode": "2259,2264"
}
};
function getState(data, postcode){
for(var x in data){
if(data[x].postcode && data[x].postcode.split(",").indexOf(postcode.toString())!=-1) return data[x].state;
}
return "Not Found";
}
alert(getState(data, "2600"));
alert(getState(data, 2264));
You can directly do .indexOf
on the postcode, even without using .split(",")
. But, then, it will also match with ,2600
which should not be the case. So, use split
.
Use json[x].postcode
condition to make sure that postcode field exists in the object. Otherwise, it will give an error if it does not exist.