How to do a filter through attribute on an object / array

3

I think it's a simple question but I'm not finding a solution to my problem.

Example:

Object:

{projectId:"1" name:"Projeto A" image:"imagem.jpg"}
{projectId:"2" name:"Projeto B" image:"imagem.jpg"}
{projectId:"3" name:"Projeto C" image:"imagem.jpg"}
{projectId:"4" name:"Projeto D" image:"imagem.jpg"}
{projectId:"5" name:"Projeto E" image:"imagem.jpg"}

I have a menu in which I am already getting the value of the id and would like to search this object through this id to load the correct image.

$('.btn').on({
    mouseenter: function () {
      $id = ($(this).attr("id"));   
    }
  }) 

Thank you very much:)

    
asked by anonymous 24.10.2017 / 13:45

3 answers

6

If you want to find 1 element then you should use .find() :

$('.btn').on({
    mouseenter: function () {
      const id = this.id;  
      const el = arr.find(obj => obj.projectId == id); 
    }
}) 
    
24.10.2017 / 13:53
5

You can use the filter function. It takes as parameter a callback that will validate each item in your collection.

Something like

mouseenter: function () {
    $id = ($(this).attr("id"));
    const filtrado = arr.filter(item => item.projectId == $id);
}

See it working.

const arr = [{ projectId:"1", name:"Projeto A", image:"imagem.jpg" },
{projectId:"2", name:"Projeto B", image:"imagem.jpg"},
{projectId:"3", name:"Projeto C", image:"imagem.jpg"},
{projectId:"4", name:"Projeto D", image:"imagem.jpg"},
{projectId:"5", name:"Projeto E", image:"imagem.jpg"}];

const id = 1; // <- Aqui seria a variável que você captura no evento 

const filtrado = arr.filter(item => item.projectId == id);

console.log(filtrado);
    
24.10.2017 / 13:48
1

I believe you should use jQuery.grep() :

var found_names = $.grep(names, function(v) {
    return v.projectId === 1;
});

DEMO

var names = [];

var object = {projectId:"1", name:"Projeto A", image:"imagem.jpg"};
names.push(object);

object = {projectId:"2", name:"Projeto B", image:"imagem.jpg"};
names.push(object);

var found_names = $.grep(names, function(v) {
    return v.projectId === "1";
});

console.log(found_names);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Just look at the console of your browser.

    
24.10.2017 / 13:50