Zi Gang
Zi Gang

Reputation: 303

How to filter with JSON postcode value and show the JSON location value (geocoding)

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"
}]

Expect Output:

if user give "32800", output value should be "Alor Kechor".

How to do that?

Upvotes: 0

Views: 59

Answers (1)

Saurabh Mistry
Saurabh Mistry

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

Related Questions