@mzvonar/setin
v0.0.19
Published
Sets value to object according to provided path and returns copy
Downloads
18
Readme
setIn
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