Skip to content

Instantly share code, notes, and snippets.

@kimmobrunfeldt
Created March 6, 2015 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kimmobrunfeldt/63c470bcb6b1679751a5 to your computer and use it in GitHub Desktop.
Save kimmobrunfeldt/63c470bcb6b1679751a5 to your computer and use it in GitHub Desktop.
Preparing for null..
// utils.jsx
// Returns wanted data or null. You can specify default value instead of null.
// Remember that arrays are actually objects so you can get index of array with
// 'arr.0'
// e.g get(object, 'data.results.0')
function get(obj, attributePath, defaultValue) {
var opts = _.extend({defaultValue: null}, {defaultValue: defaultValue});
if (!obj) {
return opts.defaultValue;
}
var returnObj = obj;
var attributes = attributePath.split('.');
for (var i = 0; i < attributes.length; ++i) {
var attribute = attributes[i];
returnObj = returnObj[attribute];
if (!returnObj) {
return opts.defaultValue;
}
}
return returnObj;
}
// IndexComponent.jsx
var Index = React.createClass({
render: function render() {
var data = this.props.data;
return (
<div className="page">
<h1>{utils.get(data, 'products.0.description')}</h1>
<h2>{utils.get(data, 'products.0.consumption')}</h2>
</div>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment