@mzvonar/setin

0.0.19 • Public • Published

setIn Build Status Coverage Status npm version

Sets value in object by path and returns copy. Path can be string or array (e.g. ['user', 'profile', 'gender']).
If any part of path doesn't exist it is created. Always returns new copy of object.

Installation

npm install @mzvonar/setin

Parameters

setIn(context, path, value, push);
Name Description
context Object in which the value will be set
path Must be Array or String. See usage
value Value to set in path
push Whether to push the value to Array. See usage

Usage

import setIn from '@mzvonar/setin';
  
const context = {
    user: {
        profile: {
            gender: 'female'
        }
    }
};
  
const newContext = setIn(context, ['user', 'profile', 'gender'], 'male');

returns:

    {
        user: {
            profile: {
                gender: 'male'
            }
        }
    }
const newContext = setIn(context, ['user', 'profile', 'address', 'country'], 'slovakia');

returns:

    {
        user: {
            profile: {
                gender: 'female',
                address: {
                    country: 'slovakia'
                }
            }
        }
    }

Push

If fourth parameter is true and last item in path is Array value is pushed to the Array

example:

    const context = {
        user: {
            name: 'Mike',
            nicknames: [
                'terminator',
                'maverick'
            ]
        }
    };
      
    const newContext = setIn(context, ['user', 'nickanmes'], 'vincent vega');
    
    console.log(newContext);
    /*
    {
        user: {
            name: 'Mike',
            nicknames: [
                'terminator',
                'maverick',
                'vincent vega'
            ]
        }
    }
    */

mutableSetIn

If you need you can import mutableSetIn, which is exactly the same as setIn, but mutates the original context object without creating copy.

Tests

npm test

Package Sidebar

Install

npm i @mzvonar/setin

Weekly Downloads

1

Version

0.0.19

License

MIT

Unpacked Size

6.78 kB

Total Files

4

Last publish

Collaborators

  • mzvonar