object-path

repository·master·Indexed 21 days ago

https://github.com/mariocasciaro/object-path

A utility library for accessing, setting, and manipulating deep properties within JavaScript objects using string or array paths. Version 0.11.8 provides methods such as get(), set(), del(), has(), coalesce(), and ensureExists(), as well as specialized array manipulation via push() and insert(). It supports creating bound instances and optional configuration to include inherited properties while protecting against prototype pollution.

Tokens
3.7K
Snippets
20
Records
20
Agent score
27%

What's inside object-path

  1. How inherited properties are handled

    master

    By default, object-path only accesses an object's own properties. If you attempt to get an inherited property, it will return undefined (or your specified default).

    To include inherited properties, you have two options:

    1. Create a new instance using create({ includeInheritedProps: true }).
    2. Use the pre-configured withInheritedProps instance.

    Security Warning: When using inherited properties mode, object-path will throw an exception if you attempt to access magic properties like __proto__ or constructor to prevent prototype pollution.

    var objectPath = require("object-path");
    
    // Option 1: Create custom instance
    var objectPathWithInheritedProps = objectPath.create({includeInheritedProps: true});
    
    // Option 2: Use built-in instance
    var objectPathWithInheritedProps = objectPath.withInheritedProps;
    
    // Usage with inherited props
    var proto = { notOwn: { prop: 'a' } };
    var obj = Object.create(proto);
    objectPath.withInheritedProps.get(obj, 'notOwn.prop'); // returns 'a'
  2. Install object-path

    master

    You can install object-path using npm or Bower. If you are using TypeScript, you can also install the typings.

    # Node.js
    npm install object-path --save
    
    # Bower
    bower install object-path --save
    
    # Typescript typings
    typings install --save dt~object-path
  3. Set values with set()

    master

    Use set(obj, path, value) to set a value at a specific path. This method will automatically create intermediate objects or arrays if they do not exist.

    var obj = {};
    var objectPath = require("object-path");
    
    objectPath.set(obj, "a.h", "m");
    objectPath.set(obj, "a.j.0.f", "m"); // creates intermediate objects/arrays
  4. Empty a path with empty()

    master

    Use empty(obj, path) to clear a path without deleting the key itself. The behavior depends on the type:

    • Primitive values are set to ''.
    • Arrays are set to [].
    • Objects are set to {}.
    • Non-inherited functions are set to null.
    objectPath.empty(obj, 'a.b'); // obj.a.b is now ''
    objectPath.empty(obj, 'a.c'); // obj.a.c is now []
    objectPath.empty(obj, 'a');   // obj.a is now {}
  5. Modify arrays with insert() and push()

    master

    Use insert(obj, path, value, index) to insert a value at a specific index within an array at the given path. Use push(obj, path, value) to append a value to an array at the given path (creating intermediate structures if necessary).

    var obj = { a: { c: ["e", "f"] } };
    var objectPath = require("object-path");
    
    objectPath.insert(obj, "a.c", "m", 1); // obj.a.c = ["e", "m", "f"]
    objectPath.push(obj, "a.k", "o");       // creates path and pushes "o"
  6. Delete paths with del()

    master

    Use del(obj, path) to remove a property from an object or an element from an array at the specified path.

    var obj = { a: { b: "d", c: ["e", "f"] } };
    var objectPath = require("object-path");
    
    objectPath.del(obj, "a.b");    // obj.a.b is now undefined
    objectPath.del(obj, ["a","c",0]); // obj.a.c is now ["f"]
  7. Ensure a path exists with ensureExists()

    master

    Use ensureExists(obj, path, defaultValue) to ensure a path exists. If the path does not exist, it sets the path to the provided defaultValue and returns the previous value (if any).

    var oldVal = objectPath.ensureExists(obj, "a.b", "DEFAULT");
  8. Bind an object to a new instance

    master

    You can create a new instance of object-path bound to a specific object. This allows you to call methods like .get(), .set(), and .del() directly on the returned object without passing the target object as the first argument.

    var objectPath = require("object-path");
    var model = objectPath({
      a: {
        b: "d",
        c: ["e", "f"]
      }
    });
    
    model.get("a.b");  // returns "d"
    model.del("a.b"); // obj.a.b is now undefined
  9. Access deep properties with get()

    master

    Use get(obj, path, [defaultValue]) to retrieve a value at a specific path. The path can be a dot-separated string or an array of keys. If the path does not exist, it returns undefined or the provided defaultValue.

    var obj = { a: { b: "d", c: ["e", "f"] } };
    var objectPath = require("object-path");
    
    objectPath.get(obj, "a.b");           // returns "d"
    objectPath.get(obj, ["a", "c", "1"]); // returns "f"
    objectPath.get(obj, "a.c.b", "DEFAULT"); // returns "DEFAULT"
  10. Delete a deep property with del()

    master

    Use del(obj, path) to remove a property at a deep path. If the parent is an array, the item is removed via splice. If the parent is an object, the property is removed via delete.

    const objectPath = require('object-path');
    const obj = { a: { b: 1, c: 2 }, d: [10, 20, 30] };
    
    // Delete object property
    objectPath.del(obj, 'a.c');
    // obj is { a: { b: 1 }, d: [10, 20, 30] }
    
    // Delete array element
    objectPath.del(obj, 'd.1');
    // obj is { a: { b: 1 }, d: [10, 30] }