dlv icon indicating copy to clipboard operation
dlv copied to clipboard

array item access?

Open quantizor opened this issue 6 years ago • 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?

quantizor avatar May 02 '19 15:05 quantizor

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

aarondancer avatar May 02 '19 20:05 aarondancer

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

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

developit avatar May 15 '19 20:05 developit

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

TimBroddin avatar May 23 '19 08:05 TimBroddin

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

ihtml5 avatar May 23 '19 15:05 ihtml5