New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

object-bystring

Package Overview
Dependencies
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

object-bystring

Access and alter objects using string literals

Source
npmnpm
Version
6.0.0
Version published
Weekly downloads
38
46.15%
Maintainers
1
Weekly downloads
 
Created
Source

object-bystring

Access and alter deeply nested object properties by string notation

Purpose

Let's say you want to change a something nested in this object:

var objA = {
  name: "tamb",
  address: {
    street: "123 fake street",
    town: "fake town",
    zip: "00000",
    state: "Fake State",
    city: "Fake City",
    POBoxes: [1234, 23213, 2321],
  },
  dependents: [
    {
      name: "John Doe",
      age: 55,
    },
    {
      name: "Jane Doe",
      age: 44,
    },
  ],
};

You coould easily write objA.dependents[1].age = 45;
Or even var indx = 1; objA.dependents[indx].age = 45;

No issue here.

But let's say you are trying to pass along an object (objB) of commands. Those commands should dictate what to change in objA.

How do you easily do this?

{
 'address.street': '345 Faker Way',
 'dependents[1].age': 45,
 'address.POBoxes[2]': 43278
}

With byString you can generate paths to object values and either set or get those values.

Latest Docs:

https://github.com/tamb/object-bystring

Demo

https://codesandbox.io/embed/object-bystring-demo-i3845d?fontsize=14&hidenavigation=1&theme=dark

installation

npm install --save object-bystring

Usage

You can import either a utility method, or a polyfill to add this functionality to the Object prototype.

// util method
const bystring = require("object-bystring");
import byString from "object-bystring";

Using the example above:

Setting Values

byString(object, key, value)

byString(objectA, "path.to.field", "new value");

Getting Values

byString(object, key);

const finger = byString(person, "arm[0].hand.fingers[3]");

const randomFinger = byString(person`arm[0].hand.fingers[${number}]`);

Attribution

Thank you, Ray for the original Stackoverflow answer, which is the majority of the source code. https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key

Check out his github and so profile below:

https://github.com/raybellis

https://stackoverflow.com/users/6782/alnitak

Keywords

object

FAQs

Package last updated on 15 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts