Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  103] [ 5]  / answers: 1 / hits: 30237  / 9 Years ago, thu, december 24, 2015, 12:00:00

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


More From » json

 Answers
72

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.


[#63954] Tuesday, December 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
georgeh

Total Points: 193
Total Questions: 103
Total Answers: 111

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
georgeh questions
Fri, Oct 8, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
Wed, Nov 25, 20, 00:00, 4 Years ago
Sat, Sep 12, 20, 00:00, 4 Years ago
Sat, Mar 7, 20, 00:00, 4 Years ago
;