Skip to content

array item access? #27

Description

@quantizor

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?

Activity

  1. aarondancer commented on May 2, 2019

    @aarondancer

    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]');
  2. developit commented on May 15, 2019

    @developit
    Owner

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

    dlv(obj, ['arr', 1])
  3. TimBroddin commented on May 23, 2019

    @TimBroddin

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

  4. ihtml5 commented on May 23, 2019

    @ihtml5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions