How to fine state name using postcode in bellow json data;
var data = '{
"1": {
"state": "VIC",
"postcode": "2600,2603,2605,2606"
},
"2": {
"state": "NSW",
"postcode": "2259,2264"
}
}'
How to find state
by postcode
;
if i search postcode 2600
if get result like VIC
We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.
If you want to identify duplicates across the entire data set, then select the entire set. Navigate to the Home tab and select the Conditional Formatting button. In the Conditional Formatting menu, select Highlight Cells Rules. In the menu that pops up, select Duplicate Values.
http://jsonlint.com/ says yes. http://www.json.org/ doesn't say anything about it being forbidden.
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.
Try like this
var data = '{"1": { "state": "VIC","postcode": "2600,2603,2605,2606"}, "2": {"state": "NSW","postcode": "2259,2264"}}';
var jsObj = JSON.parse(data);
var find = "2600";
var values = Object.keys(jsObj).filter(function(x) {
return jsObj[x].postcode.indexOf(find) > -1;
}).map(function(x) {
return jsObj[x].state;
});
console.log(values.length > 0 ? values[0] : "not found");
JSFIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With