Skip to content
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

Object.setByPath function #1129

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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
13 changes: 13 additions & 0 deletions Source/Types/Object.Extras.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ var hasOwnProperty = Object.prototype.hasOwnProperty;

Object.extend({

setByPath: function(source, path, value){
if (typeof path == 'string') path = path.split('.');
var iterator = source;
for (var i = 0, l = parts.length - 1; i++){
if (i < l){
if (typeof iterator[parts[i]] != 'object') iterator[parts[i]] = {};
iterator = iterator[parts[i]];
} else {
iterator[parts[i]] = value;
}
}
},

getFromPath: function(source, parts){
if (typeof parts == 'string') parts = parts.split('.');
for (var i = 0, l = parts.length; i < l; i++){
Expand Down
18 changes: 18 additions & 0 deletions Tests/Specs/1.3/Types/Object.Extras.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,24 @@ requires: [More/Object.Extras]
provides: [Object.Extras.Tests]
...
*/
describe('Object.setByPath', function(){

it('should set an object value by a path', function(){
var obj = {
animal: {
human: {
most_deadly: 'ninja'
}
}
};
Object.setByPath(obj, 'animal.human.most_deadly', 'chuck norris');
Object.setByPath(obj, 'animal.human.most_lovely', 'shay maria');
expect(obj.animal.human.most_deadly).toEqual('chuck norris');
expect(obj.animal.human.most_lovely).toEqual('shay maria');
});

});

describe('Object.getFromPath', function(){

it('should retrieve an object value from a path', function(){
Expand Down