How to filter an object given its partial path?
As an example.
let address = {
country :{
name:'Japan',
city:{
name:'Tokyo',
town: {
name:'korushawa'
}
},
code:'JP'
},
nearbyCountry:'Korea'
}
path1: countr.cit
For address
, path1 will result in
{
country :{
city:{
name:'Tokyo',
town: {
name:'korushawa'
}
}
}
}
For path2,
I should get entire address
object because countr is present in country
and nearbyCountry
{
country :{
name:'Japan',
city:{
name:'Tokyo',
town: {
name:'korushawa'
}
}
},
nearbyCountry:'Korea'
}
Edit: I have been able to solve this when given an exact path (ex: country.city
). But having difficulty with partial paths.
This approach rely on filtering the entries and rebuilding a new object by mapping objects with a single property.
function getParts(object, fragments) {
var [part, ...rest] = fragments.split('.');
return Object.assign({}, ...Object
.entries(object)
.filter(([key]) => key.toLowerCase().includes(part))
.map(([k, v]) => {
if (!rest.length) return { [k]: v };
var parts = v && typeof v === 'object' && getParts(v, rest.join('.'));
if (parts) return { [k]: parts };
})
);
}
let address = { country: { name: 'Japan', city: { name: 'Tokyo', town: { name: 'korushawa' } }, code: 'JP' }, nearbyCountry: 'Korea' };
console.log(getParts(address, 'countr.cit'));
console.log(getParts(address, 'countr'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With