Find and show an object of a . json by the id of the clicked element - jquery

Asked

Viewed 929 times

1

How do I search within a json for an object with a particular id, this process must take place within a function $(document).on('click', 'li', function(){});, and the id to be researched will be the id of the element li clicked, the result of the search would be the return of all the data of the element that has the id of li clicked .

Good think the explanation ta simple but ta clear, sorry I do not put code, actually I want ideas for me to research and learn, if I put the code here I will get the answer ready, not what I want, but if it is necessary I put a code example here.

1 answer

2


To know the ID of the clicked element just do var id = this.id;.

If JSON is an array:

In this case you have to go through the array comparing your ID with the key you need. In the example I also used the key id. The .find() is useful because it returns the first element of the array that fulfills the verification.

var json = [{id: 1}, {id: 2}];
$(document).on('click', 'li', function(){
    var id = this.id;
    var obj = json.find(function(_obj){
        return _obj.id == id;
    });
    console.log(obj);
});

If JSON is an Object:

In this case I imagine you want the sub-object and it gets even simpler.

var json = {id1: {foo: 'bar'}, id2: {foo: 'baz'}};
$(document).on('click', 'li', function(){
    var id = this.id;
    var obj = json[id];
    console.log(obj);
});

If this JSON comes for example by ajax you can do so:

$(document).on('click', 'li', function(){
    var id = this.id;
    $.getJSON("../file.json", function(json){
        // aqui podes usar um dos meus exemplos com Array ou Objeto
        // usando a variável "json" da callback

    }); 
});
  • I tried here but you’re returning me undefined on the console.

  • 1

    I got =D , the positioning of a variable of mine was wrong. so I was giving indefinite.

Browser other questions tagged

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