4

What is the best way to remove multiple records with a condition in extjs?

For example:

var store = Ext.create('Ext.data.Store', {
    data: [
        {name: 'Ed', age: 21},
        {name: 'Tommy', age: 15},
        {name: 'Aaron', age: 18},
        {name: 'John', age: 22}
    ]
});

I want to remove records which are 'age' is less than 20(In this case, 'Tommy' and 'Aaron'). This question could be same as how to find multiple records which much a condition.

Kohei Mikami
  • 2,850
  • 24
  • 21

4 Answers4

7

Using just the public API and keeping in mind that you probably won't want to filter the store directly or remove items one-by-one as this will trigger unnecessary redraws on any connected UI components - you could use the following:

var subCollection = store.getData().createFiltered(function(item){
    return item.get('age') < 20;
});

store.remove(subCollection.getRange());
Emissary
  • 9,954
  • 8
  • 54
  • 65
  • This is exactly what I wanted to do. Store#getData and Collection#createFiltered are available after ext 5 though. – Kohei Mikami Jan 09 '16 at 17:32
  • 1
    @KoheiMikami oh sorry I missed the Ext-4 tag - I supposed you could mimic the same behaviour with `store.getRange` and `Ext.Array.filter` for backwards compatibility. – Emissary Jan 09 '16 at 17:35
4
store.remove(
    store.queryBy(function(record) {
        ...
    }).getRange()
)

works in 4, 5 and 6.

Alexander
  • 19,906
  • 19
  • 75
  • 162
2

You probably don't want removeAll, but just to iterate and remove the ones that match

for ( var i = store.data.length; i--; ) {
    if ( store.data[i].age > 20 ) store.removeAt(i);
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • I don't want to removeAll. It probably doesn't work because if you remove records inside the iteration, the index also will be changed. But a basic idea of your code is what I want to do. – Kohei Mikami Jan 09 '16 at 17:00
0

Another approach:

// get records..

        records.forEach(function (record) {
            if (record.getData().age < 20) {
                store.remove(record);
            }
        });
xhadon
  • 876
  • 14
  • 33