Iterating through an Ember Object

前端 未结 2 1655
醉梦人生
醉梦人生 2020-12-16 00:51

I have Ember.Object which is being used as a basic key/value dictionary. The names of the keys are dynamic and what I\'d like to be able do is iterate over these properties.

2条回答
  •  离开以前
    2020-12-16 01:16

    Here are some ideas.

    Object's Keys method 1

    You can iterate over the properties and filter out the keys from the prototype chain (using the hasOwnProperty() method):

    var obj = App.MyObject.create({stuff: "stuff!"});
    
    var objKeys = []
    for(var key in obj) {
      if(obj.hasOwnProperty(key)){
        objKeys.push(key);
      }
    }
    console.log(objKeys); // ['stuff']
    

    Object's Keys method 2

    On newer browsers you can directly get an array of the object's properties using the Object.keys() method:

    console.log(Object.keys(obj)); // ['stuff']
    

    Ember.Object's computed properties

    Ember provides a way to iterate over the computed properties of a class using the eachComputedProperty() method

    App.MyObject.eachComputedProperty(function(name, meta){
      console.log(name, meta);  // randomComputedProperty
    });
    

    JSBin example demonstrating these methods

    Update

    You could have a computed property on your model that re-arranges the MyObject's data into an array which can then be displayed by handlebars:

    App.MyModel = DS.Model.extend({
      prop1: DS.attr('string'),
      prop2: DS.attr('number'),
      prop3: DS.attr('my-object'),
    
      prop3PropertyArray: function(){
        var prop3, 
            propertyArray = [];
    
        prop3 = this.get('prop3');
    
        for(var key in prop3) {
          if(prop3.hasOwnProperty(key) && key !== "toString"){
            propertyArray.push({key: key, value: prop3.get(key)});
          }
        }
    
        return propertyArray;
      }.property('prop3')
    });
    

    If prop3 contained:

    prop3: App.MyObject.create({
      stuff: "stuff!",
      anotherRandomKey: "more value here"
    })
    

    then prop3PropertyArray would be:

    [
      {
        key: "stuff",
        value: "stuff!"
      },
      {
        key: "anotherRandomKey",
        value: "more value here"
      }
    ]
    

    which can then be displayed in handlebars using an {{#each}}..{{/each}} helper:

    {{#each item in prop3PropertyArray}}
      {{item.key}} = {{item.value}}
    {{/each}}

    Updated JSBin example

提交回复
热议问题