Reputation: 21
I have a json structure that comes from a relational database of tables: countries->states->cities, the json object has this format:
var object = {
'countries': [
{
'id_country': 1,
'name': 'Country 1',
'states': [
{
'id_state': 1,
'name': 'State 1',
'cities': [
{
'id_city': 1,
'name': 'City 1'
},
{
'id_city': 2,
'name': 'City 2'
}
]
},
{
'id_state': 2,
'name': 'State 2',
'cities': [
{
'id_city': 3,
'name': 'City 3'
}
]
}
]
}
]
};
Making use of a function with parameters similar to this one:
var arrays = ['countries', 'states', 'cities'];
var keySearch = 'id_city';
var valueSearch = 3;
function getPath(object, arrays, keySearch, valueSearch);
I want to return an array like this:
var result = [0, 1, 0];
The first element of the result corresponds to the position of the country, the second of the state and the third of the city. How can I do this in javascript? I've tried to do it with a recursive method following similar examples but I haven't been able to make it work. Thanks in advance.
Upvotes: 1
Views: 73
Reputation: 5068
Very basically, fyi,
// get the first country of the object.
console.log(object.countries[0]);
// get the second state of the first country of the object.
console.log(object.countries[0].states[1]);
// get the first city of the first state of the first country of the object.
console.log(object.countries[0].states[0].cities[0]);
Upvotes: 0
Reputation: 386654
You could take a recursive approach and store the path as an object reference for each nested call.
function getPath(object, [array, ...arrays], key, value, path = []) {
object[array].some((o, i) => {
if (
o[key] === value ||
arrays.length && path.length < getPath(o, arrays, key, value, path).length
) return path.unshift(i);
});
return path;
}
var object = { countries: [{ id_country: 1, name: 'Country 1', states: [{ id_state: 1, name: 'State 1', cities: [{ id_city: 1, name: 'City 1' }, { id_city: 2, name: 'City 2' }] }, { id_state: 2, name: 'State 2', cities: [{ id_city: 3, name: 'City 3' }] }] }] };
console.log(getPath(object, ['countries', 'states', 'cities'], 'id_city', 3));
console.log(getPath(object, ['countries', 'states', 'cities'], 'id_city', 7));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1