Search code examples
javascriptjquerybackbone.jshandlebars.jslodash

How to combine JSON objects with equal values within Backbone.js


I am trying to display multiple "unread" alerts, but need to attach the organizations label to it if the organizations id is equal to the unread domainId.

How can I acheive this while displaying the results in a handlebars #each function?

JSON

"alerts" : {
    "organizations" : [ {
      "id" : 165,
      "label" : "Label #1"
    }, { 
      "id" : 170,
      "label" : "Label #2"
    }],
    "unread" : [ {
      "id" : 20022,
      "domainId" : 170,
      "created" : "2015-10-13T16:48:08Z",
    }, {    
      "id" : 20022,
      "domainId" : 165,
      "created" : "2015-10-13T16:48:08Z",
    }]
};

Backbone.js:

context: function() {
  var d = this.options.data 

  return {
    welcomeAlerts: d.alerts,
    welcomeOrg: d.alerts.organizations.label            
    }
},

Handlebars//HTMl

{{#each welcomeAlerts.unread}}
  <li class="alert-item stripe-list-item">
     <h4 class="org">{{welcomeOrg}}</h4>
     <h4 class="timestamp">{{created}}</h4>
  </li>  
{{/each}}

Solution

  • Simply transform the data beforehand

    var data = {
     "alerts" : {
        "organizations" : [ {
          "id" : 165,
          "label" : "Label #1"
        }, { 
          "id" : 170,
          "label" : "Label #2"
        }],
        "unread" : [ {
          "id" : 20022,
          "domainId" : 170,
          "created" : "2015-10-13T16:48:08Z",
        }, {    
          "id" : 20022,
          "domainId" : 165,
          "created" : "2015-10-13T16:48:08Z",
        }]
     }
    };
    
    var organizationDict = _.groupBy(data.alerts.organizations, 'id');
    
    var unreadWithOrganizations = _(data.alerts.unread)
      .map((message) => {
        return {
          ...message,
          organization: organizationDict[message.domainId]
        }
      })
      .value();
    

    and display your data

    {{#each unreadWithOrganizations}}
      <li class="alert-item stripe-list-item">
         <h4 class="org">{{organization.label}}</h4>
         <h4 class="timestamp">{{created}}</h4>
      </li>  
    {{/each}}
    

    Demo: http://jsbin.com/sadoluhepu/edit?js,console

    I've made an example using lodash library and es6. You might want to stick with ES6 and underscore, which implementation might differ.