object-traversal-by-path
TypeScript icon, indicating that this package has built-in type declarations

2.0.2 • Public • Published

Object traversal by path

Build Status

Given a path, e.g. a.b[2].c.d[1].e, it will navigate down the provided object and return the last value it finds.

You can play with it in a sandbox here

Install

npm install object-traversal-by-path or yarn add object-traversal-by-path

Usage

import { traverse } from 'object-traversal-by-path';
 
const object = {
    a: {
        b: {
            c: 'hello world!'
        }
    }
};
const path = 'a.b.c';
 
const value = traverse(path, object); // value === 'hello world!'

This also works with arrays:

import { traverse } from 'object-traversal-by-path';
 
const object = {
    a: {
        b: [
            { c: 'hello' },
            { c: 'goodbye' }
        ]
    }
};
const path = 'a.b[1].c';
 
const value = traverse(path, object); // value === 'goodbye'

Mutating

You can deeply mutate objects with the mutate function.

import { mutate } from 'object-traversal-by-path';
 
const object = {
    a: {
        b: [
            { c: 'hello' },
            { c: 'goodbye' }
        ]
    }
};
const path = 'a.b[1].c';
 
const value = mutate(path, object, () => 'see you soon!'); 
 
console.log(value.a.b[1].c); // 'see you soon!'
 

Readme

Keywords

none

Package Sidebar

Install

npm i object-traversal-by-path

Weekly Downloads

36

Version

2.0.2

License

ISC

Unpacked Size

7.9 kB

Total Files

6

Last publish

Collaborators

  • ymhr