multiple JSON filter with one function.
I am doing geocoding project now.. i can filter with 1 json file.. but how about have multiple json file with filter ?
state1.json
[{
"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"
}]
state2.json
[
{
"no": "1",
"location": "Air Putih",
"postcode": "83400",
"postOffice": "Seri Medan",
"state": "Johor"
},
{
"no": "2",
"location": "Akauntan Negeri",
"postcode": "80594",
"postOffice": "Johor Bahru",
"state": "Johor"
},
{
"no": "3",
"location": "Aked Mara",
"postcode": "83100",
"postOffice": "Rengit",
"state": "Johor"
}
]
state3.json
[
{
"no": "1",
"location": "Akauntan Negeri",
"postcode": "05594",
"postOffice": "Alor Setar",
"state": "Kedah"
},
{
"no": "2",
"location": "Alor Gelegah",
"postcode": "05400",
"postOffice": "Alor Setar",
"state": "Kedah"
},
{
"no": "3",
"location": "Alor Ibus Tepi Laut",
"postcode": "06600",
"postOffice": "Kuala Kedah",
"state": "Kedah"
}
]
I able to filter with 1 json to get value that i want :
import data from '../json/state1.json';
let jsonString = JSON.stringify(data);
let parsedData = JSON.parse(jsonString);
function findObjectByKey(parsedData, key, value) {
for (var i = 0; i < parsedData.length; i++) {
if (parsedData[i][key] === value) {
return parsedData[i]['state'];
}
}
return null;
}
let obj = findObjectByKey(parsedData, 'codes', "34200");
console.log(obj); //output Perak
How to filter with state2.json
and state3.json
together? if I type 83100
, should output Johor
. I tried to import all data in one variable but still not able to filter the value.
for some reason, I need to separate multiple JSON.
Import all the JSON data in your file. Using array#concat
join all the data in a single array. Using array#find
you can get the first matched object for a given key and value. If you are interested in getting all the matched object, replace the array#find
with array#filter
.
import data1 from '../json/state1.json';
import data2 from '../json/state2.json';
import data3 from '../json/state3.json';
function findObjectByKey(data, key, value) {
return data.find(state => state[key] === value);
}
let obj = findObjectByKey([].concat(data1,data2,data3), 'postcode', "34200");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.