Last Updated: February 25, 2016
·
2.066K
· numbers1311407

Simple nested attributes for Backbone Model

Often in Backbone I find myself working with nested data structures which I want to access individual parts of, for example a model which wraps a JSON response.

Nested path lookup in such situations can be accomplished very easily by overriding get like so:

Backbone.Model.prototype.get = function (attr) {
  if (-1 === attr.indexOf('.')) { 
    return this.attributes[attr];
  }

  return _.inject(attr.split('.'), function (o, k) {
    return o && o[k];
  }, this.attributes);
};

Say you have a model with data that looks like this:

config: {
  one: { x: 1, y: 2 },
  two: { x: 3 }
}

You can now easily access a subsection of the config, or an individual attribute, like:

model.get("config.one")   //=> {x: 1, y: 2}
model.get("config.two.x") //=> 3