developit/dlv

array item access?

quantizor opened this issue · 4 comments

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?

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

Hi @developit @TimBroddin , I have developed a similar library before and provided more powerful features.https://github.com/ihtml5/jscalpel Welcome attention