Reputation: 303
I have a JSON file.
[{
"no": "1",
"location": "Acheh Baru",
"postcode": "32000",
"postOffice": "Sitiawan",
"state": "Perak"
}, {
"no": "2",
"location": "Akauntan Negeri",
"postcode": "30594",
"postOffice": "Ipoh",
"state": "Perak"
}, {
"no": "3",
"location": "Alor Kechor",
"postcode": "32800",
"postOffice": "Parit",
"state": "Perak"
}]
if user give "32800", output value should be "Alor Kechor".
How to do that?
Upvotes: 0
Views: 59
Reputation: 13689
var arr=[{
"no": "1",
"location": "Acheh Baru",
"postcode": "32000",
"postOffice": "Sitiawan",
"state": "Perak"
}, {
"no": "2",
"location": "Akauntan Negeri",
"postcode": "30594",
"postOffice": "Ipoh",
"state": "Perak"
}, {
"no": "3",
"location": "Alor Kechor",
"postcode": "32800",
"postOffice": "Parit",
"state": "Perak"
}];
function findObjectByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
return array[i]['location'];
}
}
return null;
}
var obj = findObjectByKey(arr, 'no', "3");
console.log(obj);
Upvotes: 2