Skip to content

objectPath.modify #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,24 @@
return set(obj[currentPath], path.slice(1), value, doNotReplace);
}

/**
* Modifies an existing value using a provided function
* @param {Object} obj The object to modify
* @param {String|Array} path The path of the property to modify
* @param {Function} func The function to apply to the existing property
* @param {*} defaultValue The value to be assigned ifn none exists already
* @param {Boolean} [modifyDefault=false] Should the default value also be passed to the given function
* @return {*} [description]
* @author Seggev Shoresh <shoresh319@gmail.com>
*/
objectPath.modify = function(obj, path, func, defaultValue, modifyDefault){
var value = objectPath.get(obj, path, defaultValue);
if(modifyDefault || (defaultValue && value != defaultValue)){
value = func(value, obj, path);
}
return objectPath.set(obj, path, value);
}

objectPath.has = function (obj, path) {
if (typeof path === 'number') {
path = [path];
Expand Down