Mootools Hash.setFromPath

23 October 2009 | Sections: Computing

MooTools More implements a getFromPath method in Hash.Extras, but doesn’t provide a corresponding setter. Here’s an implementation:

Hash.implement({
    setFromPath: function(path, value) {
        var source = this;
        var prop = '';

        path.replace(/\[([^\]]+)\]|\.([^.[]+)|[^[.]+/g, function(match) {
            if (!source) return;
            prop = arguments[2] || arguments[1] || arguments[0];

            if (!(prop in source)) source[prop] = {};
            lastSource = source;
            source = source[prop];
            return match;
        });

        lastSource[prop] = value;
        return this;
    }
});

Just to explain the lastSource part, it’s a fudge to maintain object references throughout.

Comments

0 comments.

Leave a Comment

Comment details
Media Network authentication OpenID :: Media Network :: None


:'-( 8-) :-D :-x :-| :-( :-P :-) :-o ;-)