Object.setByPath function #1129

Open
wants to merge 3 commits into
from
Jump to file or symbol
Failed to load files and symbols.
+31 −0
Split
@@ -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++){
@@ -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(){