Git Product home page Git Product logo

set-value's Introduction

set-value NPM version NPM monthly downloads NPM total downloads Tests

Set nested properties on an object using dot notation.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

Install

Install with npm (requires Node.js >=11.0):

$ npm install --save set-value

Heads up!

Please update to version 3.0.1 or later, a critical bug was fixed in that version.

Usage

const set = require('set-value');

const obj = {};
set(obj, 'a.b.c', 'd');

console.log(obj);
//=> { a: { b: { c: 'd' } } }

Params

Signature:

set(object, property_path, value[, options]);
  • object {Object}: The object to set value on
  • path {String|Symbol|Array}: The path of the property to set.
  • value {any}: The value to set on obj[prop]
  • options {Object}: See all available options

Object paths

You may pass a string, symbol, or array of strings or symbols. By default, when a string is passed this library will split the string on . or a custom separator It's useful to pass an array

Escaping

Escaping with backslashes

Prevent set-value from splitting on a dot by prefixing it with backslashes:

console.log(set({}, 'a\\.b.c', 'd'));
//=> { 'a.b': { c: 'd' } }

console.log(set({}, 'a\\.b\\.c', 'd'));
//=> { 'a.b.c': 'd' }

Options

options.preservePaths

Do not split properties that include a /. By default, set-value assumes that properties with a / are not intended to be split. This option allows you to disable default behavior.

Note that this option cannot be used if options.separator is set to /.

Type: boolean

Default: true

Example

console.log(set({}, 'https://github.com', true));
//=> { 'https://github.com': true }

console.log(set({}, 'https://github.com', true, { preservePaths: false }));
//=> { 'https://github': { com: true } }

options.separator

Custom separator to use for splitting object paths.

Type: string

Default: .

Example

console.log(set(obj, 'auth/userpass/users/bob', '*****', { separator: '/' }));
//=> { auth: { userpass: { users: { bob: '*****' } } } }

options.split

Custom .split() function to use.

options.merge

Allows you to update plain object values, instead of overwriting them.

Type: boolean|function - A custom merge function may be defined if you need to deep merge. Otherwise, when merge is true, a shallow merge will be performed by Object.assign().

Default: undefined

Example

const obj = { foo: { bar: { baz: 'qux' } } };
set(obj, 'foo.bar.fez', 'zzz', { merge: true });
//=> { foo: { bar: { baz: 'qux', fez: 'zzz' } } }

Benchmarks

Benchmarks were run on a MacBook Pro 2.5 GHz Intel Core i7, 16 GB 1600 MHz DDR3.

# deep (194 bytes)
  deep-object x 823,287 ops/sec ±1.00% (90 runs sampled)
  deep-property x 1,787,990 ops/sec ±0.82% (92 runs sampled)
  deephas x 840,700 ops/sec ±0.95% (93 runs sampled)
  dot-prop x 1,249,663 ops/sec ±0.89% (90 runs sampled)
  dot2val x 2,067,212 ops/sec ±1.08% (91 runs sampled)
  es5-dot-prop x 1,668,806 ops/sec ±0.92% (92 runs sampled)
  lodash-set x 1,286,725 ops/sec ±0.82% (90 runs sampled)
  object-path-set x 1,261,242 ops/sec ±1.63% (90 runs sampled)
  object-set x 285,369 ops/sec ±0.91% (90 runs sampled)
  set-value x 2,076,931 ops/sec ±0.86% (93 runs sampled)

  fastest is set-value, dot2val (by 203% avg)

# medium (98 bytes)
  deep-object x 5,811,161 ops/sec ±1.12% (90 runs sampled)
  deep-property x 4,075,885 ops/sec ±0.91% (90 runs sampled)
  deephas x 1,508,136 ops/sec ±0.82% (92 runs sampled)
  dot-prop x 2,809,838 ops/sec ±1.16% (87 runs sampled)
  dot2val x 4,600,890 ops/sec ±0.76% (91 runs sampled)
  es5-dot-prop x 3,263,790 ops/sec ±0.97% (91 runs sampled)
  lodash-set x 3,486,628 ops/sec ±1.20% (90 runs sampled)
  object-path-set x 3,729,018 ops/sec ±0.90% (92 runs sampled)
  object-set x 973,961 ops/sec ±0.80% (92 runs sampled)
  set-value x 6,941,474 ops/sec ±1.24% (90 runs sampled)

  fastest is set-value (by 206% avg)

# shallow (101 bytes)
  deep-object x 9,416,410 ops/sec ±1.19% (89 runs sampled)
  deep-property x 5,108,536 ops/sec ±0.98% (93 runs sampled)
  deephas x 1,706,979 ops/sec ±0.98% (86 runs sampled)
  dot-prop x 4,045,902 ops/sec ±1.10% (92 runs sampled)
  dot2val x 5,862,418 ops/sec ±0.88% (91 runs sampled)
  es5-dot-prop x 4,439,646 ops/sec ±1.18% (90 runs sampled)
  lodash-set x 9,303,292 ops/sec ±1.19% (89 runs sampled)
  object-path-set x 5,657,479 ops/sec ±0.95% (93 runs sampled)
  object-set x 2,020,041 ops/sec ±0.92% (91 runs sampled)
  set-value x 11,272,227 ops/sec ±1.36% (88 runs sampled)

  fastest is set-value (by 213% avg)

Running the benchmarks

Clone this library into a local directory:

$ git clone https://github.com/jonschlinkert/set-value.git

Then install devDependencies and run benchmarks:

$ npm install && node benchmark

Comparisons to other libs, or "the list of shame"

These are just a few of the duplicate libraries on NPM.

  • bury fails all of the tests. I even wrapped it to have it return the object instead of the value, but with all of that work it still fails the vast majority of tests.
  • deep-get-set fails 22 of 26 unit tests.
  • deep-object fails 25 of 26 unit tests, completely butchered given objects.
  • deep-property fails 17 of 26 unit tests.
  • deep-set fails 13 of 26 unit tests.
  • deephas fails 17 of 26 unit tests.
  • dot-prop fails 9 of 26 unit tests.
  • dot2val fails 17 of 26 unit tests.
  • es5-dot-prop fails 15 of 26 unit tests.
  • getsetdeep fails all unit tests due to this being used improperly in the methods. I was able to patch it by binding the (plain) object to the methods, but it still fails 17 of 26 unit tests.
  • lodash.set fails 11 of 26 unit tests.
  • object-path-set fails 12 of 26 unit tests.
  • object-path fails 16 of 26 unit tests.
  • object-set fails 13 of 26 unit tests.
  • set-nested-prop fails 24 of 26 unit tests.
  • setvalue (this library is almost identical to a previous version of this library)
  • Many dozens of others

Others that do the same thing, but use a completely different API

History

v3.0.0

  • Added support for a custom split function to be passed on the options.
  • Removed support for splitting on brackets, since a custom function can be passed to do this now.

v2.0.0

  • Adds support for escaping with double or single quotes. See escaping for examples.
  • Will no longer split inside brackets or braces. See bracket support for examples.

If there are any regressions please create a bug report. Thanks!

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

  • assign-value: Assign a value or extend a deeply nested property of an object using object path… more | homepage
  • get-value: Use property paths like 'a.b.c' to get a nested value from an object. Even works… more | homepage
  • has-value: Returns true if a value exists, false if empty. Works with deeply nested values using… more | homepage
  • merge-value: Similar to assign-value but deeply merges object values or nested values using object path/dot notation. | homepage
  • omit-value: Omit properties from an object or deeply nested property of an object using object path… more | homepage
  • set-value: Set nested properties on an object using dot notation. | homepage
  • union-value: Set an array of unique values as the property of an object. Supports setting deeply… more | homepage
  • unset-value: Delete nested properties from an object using dot notation. | homepage

Contributors

Commits Contributor
87 jonschlinkert
4 doowb
2 mbelsky
1 dkebler
1 GlennKintscher
1 petermorlion
1 abetomo
1 zeidoo
1 ready-research
1 wtgtybhertgeghgtwtg

Author

Jon Schlinkert

License

Copyright © 2021, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on September 12, 2021.

set-value's People

Contributors

abetomo avatar dkebler avatar doowb avatar glennkintscher avatar jonschlinkert avatar mbelsky avatar petermorlion avatar ready-research avatar wtgtybhertgeghgtwtg avatar zeidoo 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

set-value's Issues

Whitesource scan vulnerability on set-value

Hi,

The whitesource scan detected following vulnerability on set-value package:

Name: CVE-2019-10747
Description: A vulnerability was found in set-value before 2.0.1 and from 3.0.0 before 3.0.1 previously reported as WS-2019-0176
Publish date: 2019-07-24
Resolution: Upgrade To Version 2.0.1,3.0.1

I had upgraded set-value to version 3.0.1 but still whitesource scan shows above mentioned vulnerability. Can you please check if this vulnerability still exist in latest version and can you please resolve it?

Thanks and regards,
Joginder

Final target prop set to {} first, doesn't place nice with reactive setter

Took me awhile to track this down to your package :).

I am using set-value to set a setter that's calling a rxjs next like so.

    Object.defineProperty(parent, name, {
      configurable: true,
      enumerable: true,
      get () {
        return rx.value
      },
      set (value) {
        rx.value = value
        rx.obs.next({value:value, path:path})
        self.emit(opts.event || self._rx_.event,{value:value, path:path})
        self.emit(path,value)
        self._rx_.hooks.forEach(hook=>hook.call(self,{value:value, path:path}))
      }
    })

In your code the "final" target[prop] (not the parent) is assigned a {} which after call to result is reset to the passed value. Normally no one would notice this double assignment except of course if you happen to be observing that assignment via a setter and a subscription.

    if (!isObject(target[prop])) {
      target[prop] = {};
    }

    if (i === len - 1) {
      result(target, prop, value, merge);
      break;
    }

it looks like this in my observer subscription handler an throws errors down th e line in my code cause it was expecting a primitive value not {}.

observed set value { value: {}, path: 'some.thing' }
observed set value { value: 'value that was to be set', path: 'some.thing' }

So I simply flopped the order

    if (i === len - 1) {
      result(target, prop, value, merge)
      break
    }

    if (!isObject(target[prop] && len)) {
      console.log('not object, set empty')
      target[prop] = {}
    }

and voila no assignment to {} first. Just the one firing of my observer.

Doesn't seem like this would cause any other issue in doing this and will eliminate an unnecessary conditional and assignment.

I'll fork, make this change, run your tests and submit pr.

also kinda wondering if
if (merge && isPlain(target[path]) && isPlain(value)) {
might not work as intended if isPlain doesn't resolve the setter to see if it contains a plain object or not. (i.e it thinks it's not cause it's a setter)

Dependency on is-plain-object

Would it make sense to replace the dependency on is-plain-object with:
const isPlain = obj => typeof obj === 'object'; ?

This would reduce the total number of dependencies to zero, which is always a great aim on itself.

Trying to get in touch regarding a security issue

Hey there!

I'd like to report a security issue but cannot find contact instructions on your repository.

If not a hassle, might you kindly add a SECURITY.md file with an email, or another contact method? GitHub recommends this best practice to ensure security issues are responsibly disclosed, and it would serve as a simple instruction for security researchers in the future.

Thank you for your consideration, and I look forward to hearing from you!

(cc @huntr-helper)

Setting empty object

Hi, I have been getting issues when trying to use this library.

The overall code works as it should.

However, I have some issues with the following.
The code is trying to set the property that I passed in to be an object if it is not an object. The property is an integer at the moment, and it stores the previous value that I have set.

for (let i = 0; i < len; i++) {
  let prop = keys[i];

  if (!isObject(target[prop])) {
    target[prop] = {};
  }

  if (i === len - 1) {
    result(target, prop, value, merge);
    break;
  }

  target = target[prop];
}

With this, the private value that I saved in my class, is going to be NaN instead, before it is being set to the correct value on the next parse.

So if I were to compare the previous value with the new value in my class object, it's going to see it as NaN instead of an integer that was previously set.

Backported fix for CVE-2021-23440 to 2.0.1

Hi,

According to some public reports (i.e GHSA-4jqc-8m5r-9rpr, https://www.cve.org/CVERecord?id=CVE-2021-23440)
,CVE-2021-23440 is fixed in 4.0.1 along with a backport to 2.0.1.

As is understand, this is the fix for 4.0.1: 383b72d
That was reached via 4.0.0...4.0.1.

However, when inspecting the changelog between 2.0.0 and 2.0.1 (2.0.0...2.0.1), it seems the fix for CVE-2021-23440 does not exist. This commit cb12f14 seems to be the fix for CVE-2019-10747, while CVE-2021-23440 states that CVE-2019-10747 is bypassed.

When inspecting it even furtherly, there is a pull request for fixing 2.0.1 #38, but it was not merged neither in the GH repo nor the NPM package itself.

Can you confirm the vulnerable range and the fix here (CVE-2021-23440)? It raises some confusion and I would like to make sure 2.0.1 is safe.

Thanks in advance!

Problems with Path of numbers array

// argsPath = [ '505', '508' ]
set(obj, argsPath, metrics);

returns:
{
"505": [
null,
null,
null,
null,
null,
null,
null,
null,
(508 times null) ]
}

P.S. it wasworking on on version 3.0.2

need type check for `path` argument

because this is possible currently and it fails on escape split

var set = require('set-value')
var obj = {}
set(obj, true, 'foo')
console.log(obj)

throws

/home/charlike/dev/node_modules/set-value/index.js:48
  return str.split('\\.').join(nc[1]);
             ^

TypeError: str.split is not a function

Array support causing unexpected value manipulated

Hi, there

Since our team recently upgraded set-value from v3 to v4, we found there's a severe problem dealing with numeric path.
before v4 paths are treated as properties, so it worked as expected like the following example
Screen Shot 2021-09-28 at 3 01 26 PM

but since array index supported in v4, path contains numbers that causes target object's value transformed into an array anyway, and all its properties are gone.
Screen Shot 2021-09-28 at 3 01 19 PM

the root cause might be on

set-value/index.js

Lines 148 to 150 in c574eb8

if (typeof next === 'number' && !Array.isArray(obj[key])) {
obj = obj[key] = [];
continue;

but the quandary is, how to determine a numeric path is tending to set value to an array index or an object property?

I made a codesandbox to reproduce this issue, versions switch is available on the left panel, please let me know if any further information is needed

Similar library

There's already another similar library called object-path, just FYI

Patch versions for older majors?

Hi there, any chance of releasing patch versions with the security fix for the older major versions? Many very popular libraries depend on ^2.0.0 or even 0.X. Thanks!

Feature request: Insert to Array option

I'm missing an option to insert value into Array instead of overwriting the existing value. Similar to the merge option that currently exists for Objects. Something like:

obj = {"path": {"to": {"array": ["oldValue"]}}}
set(obj, ["path", "to", "array", 0], "newValue", { insert: true ))

console.log(obj)
{"path": {"to": {"array": ["newValue", "oldValue"]}}}

I checked out the related projects but did not find a way to do this, please let me know if I missed something.

proposal (breaking change)

What you think about to force set-value to only create values if they not exists in object?
And we can use tunnckoCore/put-value(s) to only update values if they exist in the given object.

I've also created del-value (which also works as reset for deletion and will push up in a bit put-values and del-values


Brief

tunnckoCore/del-value - del(obj, key)

  • if key not string or array returns original obj
  • if obj is not an object return empty object

tunnckoCore/del-values - del(obj, key)

  • where key can be array of dot notation paths

tunnckoCore/put-value - put(obj, key, value)

  • updates value of key only if key exists
  • updates only existing values of obj when object is given to key (like assign-deep)
  • because set-value update values if exist and add if not exist
  • returns original object if key is not an object or string
  • returns empty object if obj is not an object
  • returns modified object otherwise

tunnckoCore/put-values - put(obj, key, value)

  • where key can be array of dot notation paths, as seen in del-value for now

set-value proposal - set(obj, key, value)

  • sets value only if it not exist in obj
  • if key is object, extend obj without overwriting existing values (like defaults-deep)

And all that because im writing tunnckoCore/store-cache (i'll push up in a bit) in which i want to have different methods for different behaviors - store, set, get, put, del, has. At the moment it mostly looks like option-cache but with different idea and behaviors.

Unable to run benchmark on Windows

Node sure how out-of-date your benchmarking package is, but it doesn't seem to want to run, something about the file globbing just not working

C:\Git\set-value\benchmark>node .
Error: ENOENT: no such file or directory, open 'C:\Git\set-value\benchmark\fixtures\*.js'
    at Object.openSync (node:fs:585:3)
    at Object.readFileSync (node:fs:453:35)
    at Benchmarked.toFile (C:\Git\set-value\benchmark\node_modules\benchmarked\index.js:66:22)
    at Benchmarked.toFile (C:\Git\set-value\benchmark\node_modules\benchmarked\index.js:118:18)
    at Benchmarked.addFile (C:\Git\set-value\benchmark\node_modules\benchmarked\index.js:173:17)
    at Benchmarked.addFiles (C:\Git\set-value\benchmark\node_modules\benchmarked\index.js:199:14)
    at Benchmarked.addFixtures (C:\Git\set-value\benchmark\node_modules\benchmarked\index.js:266:8)
    at Benchmarked.defaults (C:\Git\set-value\benchmark\node_modules\benchmarked\index.js:84:10)
    at new Benchmarked (C:\Git\set-value\benchmark\node_modules\benchmarked\index.js:48:8)
    at C:\Git\set-value\benchmark\node_modules\benchmarked\index.js:439:19 {
  errno: -4058,
  syscall: 'open',
  code: 'ENOENT',
  path: 'C:\\Git\\set-value\\benchmark\\fixtures\\*.js'
}

Would love to be able to run the benchmarks myself and potentially add some others to see how this library stacks up

Node 16.13.1
NPM 8.1.2
Tried in both Command Prompt/Git Bash shells
Windows 10

EDIT:
so it works on WSL, just not Windows. is there a reason why a node script (which I assume should be cross-platform) doesn't work on Windows?

Is this the expected result?

console.log(setValue({}, "{a..b}.c", "d"));
// => { '{a': { '': { 'b}': [Object] } } }

I don't think this should be the result.

Does not support named or array index correctly.

Some test cases you may want to add.

https://replit.com/@trajano/lodash#index.js

const _ = require('lodash');
const set = require('set-value');

const spec = {
  a: "foo",
  b: { x: 12, y: 11 },
  c: [
    { x: 11, y: 11 },
    { x: 22, y: 22 },
    // for keys that are strings which are 
    // reserved so simple splits can't be used
    { "foo[0].1": 22, "e.y": 22 }, 
  ],
};

console.log(spec)

const c = _.cloneDeep(spec)
_.set(c, 'b.x', 99);
_.set(c, 'c[1].y', 99);
_.set(c, "c[2]['foo[0].1']", 199);
console.log(c)

const d = _.cloneDeep(spec)
set(d, 'b.x', 99);
set(d, 'c[1].y', 99);
set(d, "c[2]['foo[0].1']", 199);
console.log(d)

Escape of \.

Escaping not working for keys with slash on the end:

'a.b\\\\.c.d' => ['a', 'b\\.c', 'd']

instead of

'a.b\\\\.c.d' => ['a', 'b\\', 'c', 'd']

CHANGELOG for v2 → v3 → v4 (list of breaking changes)

I see a number of warnings from yarn audit because some project dependencies still rely on set-value v2 and v3. While it’s technically possible to force-install v4 via package.jsonresolutions, it’s not clear whether that’s a save move or not.

It’d be great if the repo had CHANGELOG.md, UPGRADING.md, MIGRATION.md or info on the Releases page. If major versions are only related to supported Node versions or some rare edge cases, library users can make informed decisions to force-upgrade from v2 or v3.

Examples: jestCHANGELOG.md & Releases, sentry-javascriptMIGRATION.md & Releases

Related to #38 & #39

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.