动态编程:返回JavaScript中所有匹配的数据
假设我们有一个JSON对象,其中包含有关某些国家/地区的某些城市的位置的信息,例如:
const countryInfo = { country: [{ name: "Bangladesh", province: [{ name:"Dhaka", city: [{ name:"Tangail", lat: '11' }, { name:"Jamalpur", lat: '12' }] }, { name: "Khulna", city: [{ name:"Jossore", lat: '22' }, { name:"Tangail", lat: '23' }] }, { name: "Rajshahi", city: [{ name:"Pabna", lat: '33' }, { name:"Rangpur", lat: '33' }] }] },{ name: "India", province: [{ name:"West Bengal", city: [{ name:"Calcutta", lat: '111' }, { name:"Tangail", lat: '112' }] }, { name: "Uttar Pradesh", city: [{ name:"Agra", lat: '122' }, { name:"Tajmahal", lat: '123' }] }, { name: "Rajasthan", city: [{ name:"Kanpur", lat: '131' }, { name:"Jaypur", lat: '132' }] }] }] };
我们需要编写一个JavaScript函数,该函数接受一个这样的对象和一个搜索字符串。
然后,我们应该搜索与搜索字符串匹配的所有城市名称,并返回与查询匹配的所有城市对象的数组。
示例
为此的代码将是-
const countryInfo = { country: [{ name: "Bangladesh", province: [{ name:"Dhaka", city: [{ name:"Tangail", lat: '11' }, { name:"Jamalpur", lat: '12' }] }, { name: "Khulna", city: [{ name:"Jossore", lat: '22' }, { name:"Tangail", lat: '23' }] }, { name: "Rajshahi", city: [{ name:"Pabna", lat: '33' }, { name:"Rangpur", lat: '33' }] }] },{ name: "India", province: [{ name:"West Bengal", city: [{ name:"Calcutta", lat: '111' }, { name:"Tangail", lat: '112' }] }, { name: "Uttar Pradesh", city: [{ name:"Agra", lat: '122' }, { name:"Tajmahal", lat: '123' }] }, { name: "Rajasthan", city: [{ name:"Kanpur", lat: '131' }, { name:"Jaypur", lat: '132' }] }] }] }; const searchForCity = (obj, query) => { const cities = obj.country.reduce((acc, val) => { val.province.forEach(el => { el.city.forEach(elm => { acc.push(elm); }); }); return acc; },[]); const res = cities.filter(el => { return el.name === query; }); return res; }; console.log(searchForCity(countryInfo, 'Tangail'));
输出结果
控制台中的输出-
[ { name: 'Tangail', lat: '11' }, { name: 'Tangail', lat: '23' }, { name: 'Tangail', lat: '112' } ]