动态规划:返回 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' } ]
广告