最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ember JS how to get an array with unique property values - Stack Overflow

programmeradmin4浏览0评论

I have a array with objects which has different properties. There are objects with similar properties. For example,

var array=[{'property':1},{'property':2},{'property':1}]

How to get the array with unique properties using ember js?

Finally I need an array of

[{'property':1},{'property':2}]

your kind help is really appreciated.

Update: I tried the uniq() method. But that does not allow to pass the property as ember allows with sorting.

Thank You!

I have a array with objects which has different properties. There are objects with similar properties. For example,

var array=[{'property':1},{'property':2},{'property':1}]

How to get the array with unique properties using ember js?

Finally I need an array of

[{'property':1},{'property':2}]

your kind help is really appreciated.

Update: I tried the uniq() method. But that does not allow to pass the property as ember allows with sorting.

Thank You!

Share Improve this question edited Mar 11, 2015 at 14:29 Kalman 8,1311 gold badge28 silver badges45 bronze badges asked Mar 11, 2015 at 6:50 user1438823user1438823 1,3133 gold badges19 silver badges25 bronze badges 2
  • Did you tried anything, post it to see the point of issue? – Jai Commented Mar 11, 2015 at 6:55
  • 3 have a look at lodash - I use that in both node and ember apps for this sort of thing – user156888 Commented Mar 11, 2015 at 10:52
Add a ment  | 

3 Answers 3

Reset to default 9

We can do it in just one line of code using Ember's uniqBy method.

Suppose we have this array =>

var arrayName=[{'property':1},{'property':2},{'property':1}]

To get an unique array, you need to do the following =>

arrayName.uniqBy('property');

Which will return the following =>

var arrayName=[{'property':1},{'property':2}]

uniqBy returns a new enumerable that contains only items containing a unique property value. The default implementation returns an array regardless of the receiver type.(link to Ember Guide)

One way to do this is to use the filter method in conjunction with isAny method

App.IndexController = Ember.ArrayController.extend({

  unique: function(){
    var model = this.get('model');
    var uniqueObjects = [];

    return model.filter(function(item){
      if(!uniqueObjects.isAny('property', item.property)){
        uniqueObjects.push(item);

        return true;
      }

      return false;
    });
  }.property('model')
});

Working example here

Similar solution using forEach (& not forgetting to use get for item.get('property')):

unique: Em.puted('model', function() {
  var uniqueObjects = [];
  this.get('model').forEach(function(item) {
    if (!uniqueObjects.isAny('property', item.get('property'))) {
      uniqueObjects.addObject(item);
    }
  });
  return uniqueObjects;
})
发布评论

评论列表(0)

  1. 暂无评论