foreach filtering by the parameter that was passed

Asked

Viewed 191 times

1

I’m trying to solve a problem here. I believe it’s easy, but I don’t have as much intimacy with javascript yet. Next: I have a Javascript array that has some information I need, such as name and titration (example: João, Ensino Superior) The first time I call the screen, all data is loaded and populated within this array. But when I click on a button with a certain titration, it needs to load all teachers that contain that same titration and mount a grid. What I need, basically, is to foreach and filter out all the teachers that contain that particular titration. Below is the structure of Function:

function carregarDadosJ(titulacao) {
    var dataSource = data.forEach(titulacao);

    $("#divDadosDocentes").kendoGrid({
        dataSource: dataSource,
        selectable: true,
        change: onChange,
        height: 750,
        filterable: true,
        columns: [{
            field: "Nome",
            title: "Nome",
            width: 200
        }]
    });
};
  • You can give an example of the data structure of data? Is Objet? array? And titulacao is a string?

1 answer

1

Supposing titulacao be a string, and data be an object array, you can filter the array using the method .filter() array, thus:

function carregarDadosJ(titulacao) {
    // O método filter itera entre os itens da array e 
    // para cada um dos itens, a função passada será executada.
    // O filter retorna uma array com os itens os quais,
    // quando passado para a função, retorna true.
    var dataSource = data.filter(function (item, index, list) {
        // item  -> item da array
        // index -> indice do item na array
        // list  -> a própria array

        // Aqui deve ser executado o seu critério de filtro
        return item.titulacao === titulacao;
    });

    $("#divDadosDocentes").kendoGrid({
        dataSource: dataSource,
        selectable: true,
        change: onChange,
        height: 750,
        filterable: true,
        columns: [{
            field: "Nome",
            title: "Nome",
            width: 200
        }]
    });
};

Note that the original array will not be changed, the filter returns a new array with the filtered items.

Compatibility

The compatibility of the methods filter, foreach and others, specified in ecmascript version 5, are not compatible with older browsers and IE < 9. If you need this compatibility, use the lodash, that changes practically nothing of the syntax:

var dataSource = _.filter(data, function (item, index, list) { ... });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.