How to get the index of a javascript object searching for the value?

Asked

Viewed 9,733 times

3

I have such a JS object (fictitious values):

{
aifuw    :    7,
hsjwo    :    5,
hsgqk    :    137,
jskwe    :    9483,
NNNNN... :    N...
}

I need to get the index where the value is 137. The ways I tried didn’t work out.

5 answers

5


You need to iterate all object properties (except inherited ones), until you find the value of the one you want:

function chavePorValor(obj, val) {
    for(var chave in obj) {
        if(obj[chave] === val && obj.hasOwnProperty(chave)) {
            return chave;
        }
    }
}

var dados = {
    aifuw    :    7,
    hsjwo    :    5,
    hsgqk    :    137,
    jskwe    :    9483
};
chavePorValor(dados, 137); // hsgqk

Note: If there is more than one key with the same value, the function will return the first one it finds (usually the first one to have been declared in the object, but Javascript does not guarantee the order of the object’s keys).

3

You can iterate in properties like this: suppose your object is called obj then you can do

for(prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        if (obj[prop] === 137) {
            indice = prop;
            break;
        }
    }
}

Basically, for (prop in obj) is a for loop that iterates in all properties of the object and prop is a string with the name of the current property in the loop. The if it is used to verify if the property is actually of the object and not of the prototype. If it is of the object then it is verified if the value is 137 (your example) arrow the index and exit the loop.

This still has a problem, you can have several properties with that value, so it makes more sense to return all (the above code only returns the first), in which case you would have to take the break. Basically, this makes more sense in a function, for example:

function encontraPropriedadesComValor(objeto, valor) {
    var nomesPropriedades = [];
    for(prop in objeto) {
        if (objeto.hasOwnProperty(prop)) {
            if (objeto[prop] === valor) {
                nomesPropriedades.push(prop);
            }
        }

    }
    return nomesPropriedades;
}

2

See if that’s what you’re looking for.

var objeto = 
{
  aifuw : 7,
  hsjwo : 5,
  hsgqk : 137,
  ahayh : 137,
  jskwe : 9483,
}

function procurarporChave(obj, value)
{
    return Object.keys(obj).filter(function(key) 
    {
      return obj[key] == value;
    })
}

var valor = '137';

chaves = procurarporChave(objeto, valor);
alert(chaves); // hsgqk, ahayh

Jsfiddle

1

If you are going to use the underscore library

suggest doing so.

   _.each({
   aifuw    :    7,
   hsjwo    :    5,
   hsgqk    :    137,
   jskwe    :    9483,
   NNNNN... :    N...
   }, function(element, key) { element == 137 ? alert(key) : "" });

jsfile

0

Another possibility would be with (one more) solution proposed by the PHPJS based on array_search() of PHP:

function array_search(needle, haystack, argStrict) {
  //  discuss at: http://phpjs.org/functions/array_search/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //    input by: Brett Zamir (http://brett-zamir.me)
  // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //  depends on: array
  //        test: skip
  //   example 1: array_search('zonneveld', {firstname: 'kevin', middle: 'van', surname: 'zonneveld'});
  //   returns 1: 'surname'
  //   example 2: ini_set('phpjs.return_phpjs_arrays', 'on');
  //   example 2: var ordered_arr = array({3:'value'}, {2:'value'}, {'a':'value'}, {'b':'value'});
  //   example 2: var key = array_search(/val/g, ordered_arr); // or var key = ordered_arr.search(/val/g);
  //   returns 2: '3'

  var strict = !! argStrict,
    key = '';

  if (haystack && typeof haystack === 'object' && haystack.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
    return haystack.search(needle, argStrict);
  }
  if (typeof needle === 'object' && needle.exec) { // Duck-type for RegExp
    if (!strict) { // Let's consider case sensitive searches as strict
      var flags = 'i' + (needle.global ? 'g' : '') +
        (needle.multiline ? 'm' : '') +
        (needle.sticky ? 'y' : ''); // sticky is FF only
      needle = new RegExp(needle.source, flags);
    }
    for (key in haystack) {
      if (needle.test(haystack[key])) {
        return key;
      }
    }
    return false;
  }

  for (key in haystack) {
    if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
      return key;
    }
  }

  return false;
}

Demonstration in Jsfiddle.

It follows the same idea as the other answers, however, because it is a port of a language resource, includes an additional feature that may come in handy.

Browser other questions tagged

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