How to filter data from a JSON with JS?

Asked

Viewed 5,337 times

9

Guys, wanted to know how to make a "select" inside a JSON file using JS.

Example:

Esse é o exemplo

I have a table below using data coming from a JSON file, but I wanted to make a filter so when click search, it drop in the table the result.

Note: I don’t know much about JS frameworks, but if it’s easier, I don’t care.

For example use this JSON:

[
    {
        "id": "1",
        "nome": "Pedro",
        "console": "ps2",
        "preco": "200"
    },
    {
        "id": "2",
        "nome": "Val",
        "console": "ps1",
        "preco": "50"
    },
    {
        "id": "3",
        "nome": null,
        "console": "xbox",
        "preco": "2000"
    },
    {
        "id": "4",
        "nome": "Flavio",
        "console": "one",
        "preco": "1000"
    },
    {
        "id": "5",
        "nome": "Giovanna",
        "console": "xbox98",
        "preco": "300"
    },
    {
        "id": "6",
        "nome": "Luana",
        "console": "xbox",
        "preco": "200"
    },
    {
        "id": "7",
        "nome": "Pri",
        "console": "ps2",
        "preco": "100"
    }
]

2 answers

7


Once you create the table from this JSON the best is to cache these DOM elements (<tr>) and associate with your initial object so you can work with them later.

That is, if you add to each of these objects a property, for example DOM, you can then (effortlessly for the browser) fetch the element you want and hide it if the filter does not apply to it.

An example would be:

data.map(function (pessoa) {
    var tr = document.createElement('tr');
    Object.keys(pessoa).forEach(function (valor) {
        var td = document.createElement('td');
        td.innerHTML = pessoa[valor];
        tr.appendChild(td);
    });
    table.appendChild(tr);
    pessoa.DOM = tr;
    return pessoa;
});

So from your JSON that I called data, you can map it to have on each object (called pessoa in the code) the original content plus a new property pessoa.DOM = tr;.

So you can then filter only JSON without going to the DOM, which is much more efficient. Then you can use CSS classes to hide what you don’t want:

button.addEventListener('click', function () {
    var prop = select.value;
    var val = input.value;
    data.forEach(function (linha) {
        var valor = linha[prop];
        if (valor && linha[prop].indexOf(val) < 0) linha.DOM.classList.add('esconder');
        else linha.DOM.classList.remove('esconder');
    });
});

Example: http://jsfiddle.net/cjwoumey/

5

I made a simple code in pure JS based on your form. It’s very simple, I would have to improve:

Being json the variable with the json of your data, select the combo where values are the name of the columns (case properties) contained in json and query the element text from your form. Access the demo below to understand.

The code of the filter button("Research" in your case) the data:

document.getElementById("filter").onclick = function() {
    var result = json.filter(function(item) {
        return item[select.value] == query.value;
    });
};

Fiddle

The idea is to use the Array.filter() javascript.

Other examples with string filter being of type contains, startsWith and endsWith.

Updated demo with json posted.

Updated demo with table generation.

  • Dont, would it be possible for you to make these codes functional? I couldn’t quite understand the examples.. Like, show the return of the filter in a tabelinha, just so I can see what happened better..

  • @Giovannibernini why don’t you put a console.log(...) on each line to see what you need? or better, why not debug and see what happens on each line?

  • @Giovannibernini put a demo using his data, and also that demo with the code all commented. I recommend opening the console and going debugging line by line(F10) to understand - I have already left a debugger there on purpose.

  • @Dontvotemedown I managed to better understand the code now, but I have some doubts, because the result does not appear? Was it intentional? Also I don’t know how to debug from the console (I believe this console is the browser one, but I don’t know how to debug it), web is kind of new for me. I’ll do some research on this, but thanks in advance!

  • 1

    @Giovannibernini yes, it was intentional. I used the command console.log to display the results. To debug through the console, you open the console with the F12 key and then give a Run on the page. Clicking will stop on breakpoint, which is the command debugger in the code. Then just debug with F10 or F11, hovering over the variables to see the values. Always good also search the commands you do not know, I suggest this site: https://developer.mozilla.org/en-US/

  • @Dontvotemedown Aah, has to give the Run, so there was nothing appearing on the console, got it. How would I get this [result] and download into a table?

  • @Giovannibernini to create a table with the data you have to assemble the elements and display them in html. You can do this the hard way with plain html or jQuery, which you prefer?

  • @Dontvotemedown’s Prefer with jQuery, it will be more complicated to understand, more I manage. Thanks even there Dont, bitch help you are giving me!!

  • @Giovannibernini takes a look at the last demo I posted.

Show 4 more comments

Browser other questions tagged

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