Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including object-traversal-by-path with all npm packages installed. Try it out:

var objectTraversalByPath = require("object-traversal-by-path")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

object-traversal-by-path v2.0.2

Simple object navigation

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!'

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free