Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Object.setByPath function #1129

Open
wants to merge 3 commits into from

3 participants

@upsolution

Usage example:

var obj = {};
Object.setByPath(obj, 'very.long.path', 'value');
// obj.very.long.path = "value";
Ruslan Sukhar added some commits
@upsolution

This pull closes #264 and #1074

@piotr-cz

+1 quite helpful with current Object.getFromPath, especially with Hash.Cookie which doesn't work well with nexted objects.

One could use with some tweaking:

var Store = new Hash.Cookie( 'store' );
Store.setByPath( 'state.isNew', true );
@stutteringp0et

Why not?:

    Object.extend({
        setFromPath:function(object,paths,value){
            var paths = paths.split('.');
            var traverse = function(context,pathStack){
                var currPath = pathStack.shift();
                if ((typeof context[currPath]) == "object" && pathStack.length){
                    traverse(context[currPath], pathStack);
                }else{
                    context[currPath] = value;
                }
            };
            traverse(object,paths);            
        }
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on May 23, 2012
  1. Tests for Object.setByPath

    Ruslan Sukhar authored
  2. Object.setByPath tests syntax fix

    Ruslan Sukhar authored
  3. Object.setByPath function

    Ruslan Sukhar authored
This page is out of date. Refresh to see the latest.
View
13 Source/Types/Object.Extras.js
@@ -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++){
View
18 Tests/Specs/1.3/Types/Object.Extras.js
@@ -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(){
Something went wrong with that request. Please try again.