I have developed a basic dynamic program that can retrieve the first matched data. However, I now aim to extract all matched data from my dataset:
let countryList = {
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'
}]
}]
}]
}
In this dataset, there are two countries with provinces and cities. Users can search for any input like country, province, or city. For instance, searching for Tangail
should return all 3 results.
Desired Output:
[{
name:"Tangail",
lat: '11'
},{
name:"Tangail",
lat: '23'
}, {
name:"Tangail",
lat: '112'
}]
I have attempted the following approach :
function findName(obj, name) { return obj.name.trim() === name; }
function information( countryList, searchValue, current, state ) {
let nextState; // state is used to prevent call of undefined data
if ( state === "province" ) {
nextState = "city"; current = "country";
} else if( state === "city" ) {
nextState = "empty"; current = "province";
} else {
nextState = ""; current = "city";
}
// search matching data
let data = countryList.find( val => findName( val, searchValue ) );
// if not data found
if( typeof data === 'undefined' && nextState !== '' ) {
let len = countryList.length;
for( let x = 0; x < len; x++ ) { // now search all immediate child data
let status = {};
status.name = countryList[x].name;
status.lebel = current;
let info;
info = information(countryList[x][state], searchValue, current, nextState); // recursive call
if( typeof info !== 'undefined' ) { // if data found
return { state: status, data: info };
}
}
// return results;
} else {
return data;
}
}
let state = "province";
let current = "country";
let searchValue = "Tangail";
let abc = information( countryList.country, searchValue, current, state);
console.log("abc : ", abc);
However, the output always shows the first matched value only.
Any recommendations? Thank you!
Note: This project is implemented in javascript