Search code examples
ember.jschartsember-data

How to map model data to a chart-friendly array in ember.js


I have a model in a route that has data i'd like to chart using a chart plugin (ember-google-charts or ember-charts specifics do not matter to my issue)

in routes/server.js:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return Ember.RSVP.hash({
      stats: this.store.query('stat', {filter: {serverId: params.server_id}})
      server: this.store.findRecord('server', params.server_id),
    })
  },
  setupController(controller, models) {
    controller.setProperties(models);
  }
 }
});

My issue where/how to make stats into a proper array (using timechecked and players attributes) in order to pass the data into a charting plugin in the template.

I've tried something similar to:

stats: this.store.query('stat', {filter: {serverId: params.server_id}}).then(items => {
    //modify items here

})

but i have a hard time figuring out how to manipulate the data and build a new array without throwing errors using a forEach (which exists on the ember Array class)


Solution

  • 1.You can use forEach to iterate and return result you created. refer this answer for work with ember model

    stats: this.store.query('stat', { filter: { serverId: params.server_id } }).then(items => {
            //modify items here
            let result =[];
            items.forEach(function(element) {
              let value1 = element.get('propertyName');
              result.pushObject(value1);          
            }, this);
            return result;
        })
    

    2. If you just want plain array then you can use toArray method.