Skip to content
Open
Show file tree
Hide file tree
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
15 changes: 15 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,21 @@
return set(obj[currentPath], path.slice(1), value, doNotReplace);
}

/**
* Updates 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 used by the function if none exists already
* @return {Object} The modified object
* @author Jared Rewerts <jaredrewerts@gmail.com>
*/
objectPath.update = function(obj, path, func, defaultValue, modifyDefault){
var value = objectPath.get(obj, path, 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
28 changes: 28 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,34 @@ describe('set', function() {
});
});

describe('update', function() {
it('should update an existing array of values', function() {
var obj = getTestObj();
objectPath.update(obj, ['b', 'd'], function(value, object, path) {
var newValue = []
for (var i = 0; i < value.length; i++) {
newValue.push(value[i].charCodeAt(0))
}
return newValue;
})
expect(obj.b.d[0]).to.be.equal(97)
expect(obj.b.d[1]).to.be.equal(98)
});

it('should update an array of values that doesn\'t exist', function() {
var obj = getTestObj();
objectPath.update(obj, ['b', 'z'], function(value, object, path) {
var newValue = []
for (var i = 0; i < value.length; i++) {
newValue.push(value[i].charCodeAt(0))
}
return newValue;
}, ['x', 'y', 'z'])
expect(obj.b.z[0]).to.be.equal(120)
expect(obj.b.z[1]).to.be.equal(121)
expect(obj.b.z[2]).to.be.equal(122)
});
});

describe('push', function() {
it('should push value to existing array using unicode key', function() {
Expand Down