Rescue the index of an object with a certain attribute within an object array

Asked

Viewed 1,981 times

1

I have the following in javascript:

var listaImagens = [{"idImagem":4,"arquivo":"illustration_transport-04.svg","idCategoria":1,"nomeCategoria":"Transportes","modificacoes":[{"id":"sxqae3wtj1h2rzfr","cor":"#ff6500"},{"id":"egltjnqi7ut2zkt9","cor":"#FFFFFF"},]},{"idImagem":5,"arquivo":"casa.svg","idCategoria":2,"nomeCategoria":"Construcoes","modificacoes":[{"id":"aksjdhauhkuhksee","cor":"#fcdd10"},{"id":"lasdweiefnswekej","cor":"#FFCD00"},]};

How do I find the index of the object that has "idCategory" = 2.

Any suggestions?

3 answers

3

An option I would adopt:

var indice = listaImagens.indexOf(listaImagens.filter(function(obj){
    return obj.idCategoria == 2;
})[0]);

Jsfiddle: http://jsfiddle.net/ruipimentel/cfLmLrex/

1. Explanation

Filter function() [ Array.prototype.filter ]

It is available throughout the Array. It takes as its first parameter a function; this function is called callback, and is executed (by the function filter()) once for each element of the array. The function filter() has as output the array itself, however filtrate.

The callback function is who performs this filtering, rounding true (keep) or false (cut) for each element of the array. This function is based on up to 3 parameters (below) for this choice, but in my case I chose to receive from the function filter() only the first:

  • [Mandatory] current array element (in my case, obj);
  • [Optional] index of this element in the array;
  • [Optional] a reference to the array being traversed;

In my example, I made only the elements with the condition obj.idCategoria == 2 return true and therefore eliminated the other elements of the array.

Index function() [ Array.prototype.indexof ]

This function returns to us the index of an element within the array. For this, it strictly determines (===), the equality of the given parameter with each element of the array. In the case of literal objects, as is the case here, the strict comparison will only return true if the parameter is a reference an array element. For this reason, filtering was required (filter()) and selection of the first element of the post-filtering array ([0]).

2. Addressing this problem in the near future

The future reserves us an even more practical method of discovering the index of an element within an array. Firefox was the first to run ahead and implement a proposed function in Ecmascript6, called findIndex(), and also available in the prototype Array [ Array.prototype.findIndex ].

It works very similar to functions map() and filter(), receiving a callback function as a parameter that will be executed in sequence by each element of the array; as soon as a callback execution returns true, the element index will be returned by the function findIndex().

In this way, the code could be further reduced to:

var indice = listaImagens.findIndex(function(obj){
    return obj.idCategoria == 2;
});

recalling, once again, that the implementation of this function has not been completed in most browsers, including the latest versions of Google Chrome.

2


0

You can use the function filter or foreach array. The advantage of the first is that you can pick up the full item:

var auxIndex = -1;

// com filter
var item = listaImagens.filter(function(i, idx) {
    if(i.idCategoria == 2) {
        auxIndex = idx;
        return true;
    }
    return false;
})[0];

// com forEach
listaImagens.filter(function(i, idx) {
    if(i.idCategoria == 2)
        auxIndex = idx;
});

In both roles, i is the current and idx is the index of.

Browser other questions tagged

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