具有一个功能的多个JSON过滤器。
我现在正在进行地理编码项目..我可以使用1个json文件进行过滤..但是有多个带过滤器的json文件怎么样?
state1.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"
}
]
state2.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"
}
]
state3.json
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
我能够用1 json过滤以获得我想要的值:
state2.json
如何一起过滤state3.json
和83100
?如果我输入Johor
,则应输出{{1}}。我试图在一个变量中导入所有数据,但仍然无法过滤该值。
由于某种原因,我需要分离多个JSON。
答案 0 :(得分:2)
导入文件中的所有JSON数据。使用array#concat
连接单个数组中的所有数据。使用array#find
,您可以获得给定键和值的第一个匹配对象。
如果您有兴趣获取所有匹配的对象,请将array#find
替换为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");