-
Notifications
You must be signed in to change notification settings - Fork 41
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
array item access? #27
Comments
Dot notation can be used for accessing array items as well: const obj = { arr: [32, 23, 1234] };
dlv(obj, 'arr.1'); Supporting brackets is pretty straight forward, I'm sure there's a more succinct or performant alternative but here's the gist: function dlv(obj, key, def, p) {
p = 0;
key = key.split ? key.replace(/\[([\w\d]+)\]/g, '.$1').split('.') : key;
while (obj && p<key.length) obj = obj[key[p++]];
return (obj===undefined || p<key.length) ? def : obj;
}
const obj = { arr: [32, 23, 1234] };
dlv(obj, 'arr[1]'); |
You can already use an array key, which is better than constructing a string for offset-based access: dlv(obj, ['arr', 1]) |
I once tried to solve this problem too: https://github.com/TimBroddin/data-diver/blob/master/src/index.js I tested to see if the child was an array or an object, but I'm not sure if that's necessary :) |
lodash.get allows for something like this:
which would correspond to:
Any chance this could be supported in dlv as well?
The text was updated successfully, but these errors were encountered: