Question

How do I make an array of objects unique based on a property? In this instance, "field":

0: Object
field: "name"
operator: "eq"
value: "d"

1: Object
field: "gridSearch"
operator: "contains"
value: "1"

2: Object
field: "gridSearch"
operator: "contains"
value: "12"

For reference here is the bit of code I'm using where this problem is concerned:

$('#gridSearch').keyup(function() {
    var currentFilters = $('.k-grid').data("kendoGrid").dataSource.filter();

    currentFilters.filters.push({
        field: 'gridSearch',
        operator: 'contains',
        value: $(this).val()
    })

    console.log(currentFilters.filters)
})
Was it helpful?

Solution

You can use jQuery.extend for this; since you want to use this for a Kendo Grid, maybe you could do something like this (example only works for filters without nesting):

kendo.ui.Grid.fn.addOrUpdateFilter = function (filter) {
    var filterConfig = this.dataSource.filter(),
        filters,
        isNewFilter = true;

    if (filterConfig) {
        filters = filterConfig.filters;
        for (var i = 0; i < filters.length; i++) {
            if (filters[i].field === filter.field) {
                // there already was a filter for this field, so update it
                $.extend(filters[i], filter);
                isNewFilter = false;
            }
        }
    } else {
        filters = [];
    }

    // there was no filter for this field, so add it
    if (isNewFilter) {
        filters.push(filter);
    }

    this.dataSource.filter(filters);
}

so you could do this in your handler:

$('#gridSearch').keyup(function() {
    var grid = $('.k-grid').first().data("kendoGrid");

    grid.addOrUpdateFilter({
        field: 'gridSearch',
        operator: 'contains',
        value: $(this).val()
    });
})

OTHER TIPS

If I understand it correctly you want to define a method so that when you push new elements, it doesn't already exist. It sounds to me like you need to add another step:

var addUniqueElement = function(arr, el) {
   for(var i = 0; i < arr.length; i++) {
      if(arr[i].field == el.field)
         return false; // This element already exists
   }
   // Element didn't already exist in the array
   arr.push(el);
   return true;
}

Then all you need to do is call addUniqueElement instead of pushing it yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top