Issue
Suppose I got an object defined as such:
const me = {
id: 1,
name: 'James',
age: 40,
family: {
mother: {
id: 101,
name: 'Bea',
age: 66
},
father: {
id: 102,
name: 'Martin',
age: 69
},
children: [
{
id: 11,
name: 'Tom',
age: 18,
},
{
id: 12,
name: 'Nancy',
age: 13,
},
],
},
}
How does one easily access a value by just giving an array of strings of the chained properties' names? For example, calling:
search(me, ['family', 'father', 'age'])
which would be the same as:
me['family']['father']['age']
would return 69.
PS:
What about having search(me, ['family', 'children', 'name']) return ['Tom', 'Nancy']?
PSS:
Or even search(me, ['family', 'children', ['name', 'age']]) returning
[
{
name: 'Tom',
age: 18
},
{
name: 'Nancy',
age: 13
}
]
EDIT: I went checking out lodash/deepdash libraries, but couldn't really figure it out by myself.
Solution
You can do that with this simple recursive function which takes an array as the query:
const me = {
id: 1,
name: 'James',
age: 40,
family: {
mother: {
id: 101,
name: 'Bea',
age: 66
},
father: {
id: 102,
name: 'Martin',
age: 69
},
children: [
{
id: 11,
name: 'Tom',
age: 18,
},
{
id: 12,
name: 'Nancy',
age: 13,
},
],
},
}
function search(obj, [first, ...rest]) {
return rest.length ? search(obj[first], rest) : obj[first];
}
const result = search(me, ['family', 'father', 'age']);
console.log(result);
Answered By - Guerric P
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.