Skip to content
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

Open
quantizor opened this issue May 2, 2019 · 4 comments
Open

array item access? #27

quantizor opened this issue May 2, 2019 · 4 comments

Comments

@quantizor
Copy link

lodash.get allows for something like this:

get(obj, 'foo[0]')

which would correspond to:

obj = {
  foo: [
    'x' // <-
  ],
}

Any chance this could be supported in dlv as well?

@aarondancer
Copy link

aarondancer commented May 2, 2019

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]');

@developit
Copy link
Owner

developit commented May 15, 2019

You can already use an array key, which is better than constructing a string for offset-based access:

dlv(obj, ['arr', 1])

@TimBroddin
Copy link

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 :)

@ihtml5

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants