GithubHelp home page GithubHelp logo

developit / dlv Goto Github PK

View Code? Open in Web Editor NEW
1.2K 9.0 41.0 26 KB

Safe deep property access in 120 bytes. x = dlv(obj, 'a.b.x')

Home Page: https://npm.im/dlv

JavaScript 100.00%
object javascript key dlv

dlv's Introduction

dlv(obj, keypath) NPM Build

Safely get a dot-notated path within a nested object, with ability to return a default if the full key path does not exist or the value is undefined

Why?

Smallest possible implementation: only 120 bytes.

You could write this yourself, but then you'd have to write tests.

Supports ES Modules, CommonJS and globals.

Installation

npm install --save dlv

Usage

delve(object, keypath, [default])

import delve from 'dlv';

let obj = {
	a: {
		b: {
			c: 1,
			d: undefined,
			e: null
		}
	}
};

//use string dot notation for keys
delve(obj, 'a.b.c') === 1;

//or use an array key
delve(obj, ['a', 'b', 'c']) === 1;

delve(obj, 'a.b') === obj.a.b;

//returns undefined if the full key path does not exist and no default is specified
delve(obj, 'a.b.f') === undefined;

//optional third parameter for default if the full key in path is missing
delve(obj, 'a.b.f', 'foo') === 'foo';

//or if the key exists but the value is undefined
delve(obj, 'a.b.d', 'foo') === 'foo';

//Non-truthy defined values are still returned if they exist at the full keypath
delve(obj, 'a.b.e', 'foo') === null;

//undefined obj or key returns undefined, unless a default is supplied
delve(undefined, 'a.b.c') === undefined;
delve(undefined, 'a.b.c', 'foo') === 'foo';
delve(obj, undefined, 'foo') === 'foo';

Setter Counterparts

  • dset by @lukeed is the spiritual "set" counterpart of dlv and very fast.
  • bury by @kalmbach does the opposite of dlv and is implemented in a very similar manner.

License

MIT

dlv's People

Contributors

billneff79 avatar cweili avatar developit avatar greenkeeper[bot] avatar k1r0s avatar kalmbach avatar lukeed avatar rreverser avatar tusbar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dlv's Issues

types (TypeScript)

Hey! 👋

Thanks for this little gem 💎

I'm wondering are you open to committing TS type declaration to the repo? Or should I add them to DefinitelyTyped repo?

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of microbundle is breaking the build 🚨

Version 0.4.5 of microbundle was just published.

Branch Build failing 🚨
Dependency microbundle
Current Version 0.4.4
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

microbundle is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 63 commits.

  • 6a95870 0.4.5
  • 41e0dc3 Fix mangle.json name caching (seemed to break in a recent rollup update)
  • 42050bb Fix Rollup upgrade adding __esModule properties to exports.
  • 0a6a791 Merge pull request #161 from philipp-spiess/patch-1
  • 1ffccee Add react-recomponent to "Built with Microbundle"
  • bf2d068 Updated rollup to 0.60.1, made code changes to support it (#151)
  • 8286def Merge pull request #153 from mattdesl/fix/111
  • fcbfa8f Merge pull request #149 from developit/greenkeeper/pretty-bytes-5.1.0
  • d786f03 fix #111 and log errors during watch
  • 8393af2 fix(package): update pretty-bytes to version 5.1.0
  • 818a7d5 Revert "Update rollup to the latest version 🚀" (#148)
  • c7fbe3e Merge pull request #145 from developit/greenkeeper/rollup-0.60.0
  • 9d77676 fix(package): update rollup to version 0.60.0
  • 4d5ff56 Turn off eslint rules inconsistent with prettier settings and run prettier through eslint (#136)
  • 3afc4f4 Merge pull request #140 from developit/greenkeeper/rollup-0.59.3

There are 63 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

array item access?

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?

undefined key throws

From the readme:

//undefined obj or key returns undefined, unless a default is supplied
delve(undefined, 'a.b.c') === undefined;
delve(undefined, 'a.b.c', 'foo') === 'foo';
delve(obj, undefined, 'foo') === 'foo';

Feature: Default when not found

I've found us doing this pattern a lot when using dlv:

let foo = dlv(bar, 'a.b.c');
if(typeof foo === 'undefined') foo = defaultFoo;

It might be useful to allow dlv to support a third argument that is a default return value if the key is not found

Shorter version

Smallest possible implementation: only 120 bytes.

There's possibly smaller version:

export dlv = (obj, key) => (key.split ? key.split('.') : key).reduce((a,b)=>b?a?.[b]:a,obj)

Default is working wrong for nested null value

import delve from 'dlv'

let obj = {
  a: {
    c: 1,
    d: undefined,
    e: null
  }
}

console.log(delve(obj, 'a.c', 'default')) // 1
console.log(delve(obj, 'a.c.f', 'default')) // default

console.log(delve(obj, 'a.d', 'default')) // default
console.log(delve(obj, 'a.d.f', 'default')) // default

console.log(delve(obj, 'a.e', 'default')) // null
console.log(delve(obj, 'a.e.f', 'default')) // null <- bug

The last one is nested key over null value, it doesn't exist but returns null instead of default value.

130 bytes is smallest possible?

If you make a statement like that you can always count on a smart ass to respond

  • p can be declared as default value
  • split('.') can be written as split`.`
  • length is used twice

How about something like:

export default dlv = (
    obj,
    key,
    def,
    p=0,
    k=key.split ? key.split`.` : key,
    l=k.length
) => {
           while (obj && p<l) obj = obj[k[p++]];
           return (obj===undefined || p<l) ? def : obj;   
}

... haven't tested it

Or to get rid of the return

export default dlv = (
    obj,
    key,
    def,
    p=0,
    k=key.split ? key.split`.` : key,
    l=k.length,
    o=(_=>{while (obj && p<l) obj = obj[k[p++]]})()
) => (obj===undefined || p<l) ? def : obj;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.