Access and alter deeply nested object properties by string notation
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.
https://github.com/tamb/object-bystring
https://codesandbox.io/embed/object-bystring-demo-i3845d?fontsize=14&hidenavigation=1&theme=dark
npm install --save object-bystring
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:
byString(objectA, "path.to.field", "new value");
setting values for fields that don't exist will add them to the object. Setting values for array indexes that don't exist will add them to the array and other indexes will be undefined.
### Getting Values
#### `byString(object, key);`
```js
const finger = byString(person, "arm[0].hand.fingers[3]");
const randomFinger = byString(person`arm[0].hand.fingers[${number}]`);
Getting values for fields that don't exist will return undefined
.
Thank you, Ray for the original Stackoverflow answer, which is the inspiration for the source code. https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key
Check out his github and so profile below: