How do I get the index of a javascript object by looking for the value?

3

I have a JS object like this (dummy values):

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

I need to get the index where the value is 137 . The forms I tried did not work.

    
asked by anonymous 31.05.2014 / 01:56

5 answers

5

You have to iterate all the properties of the object (except the 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 returns the first one it finds (usually the first one declared in the object, but JavaScript does not guarantee the order of the object's keys). >     

31.05.2014 / 02:07
3

You can iterate in properties like this: suppose your object is called obj so 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 across all object properties, whereas prop is a string with the name of the current property in the loop. Verifying if is used to verify that the property is actually the object, not the prototype. If it is of the object then it is checked if the value is 137 (its example) arrow is the index and leaves the loop.

This still has a problem, you can have multiple properties with that value, so it makes more sense to return all (the code above 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;
}
    
31.05.2014 / 02:09
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

    
31.05.2014 / 02:08
1

If you are going to use the underscore library

I suggest doing it that way.

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

jsfile

    
31.05.2014 / 02:29
0

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

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;
}

Demo in JSFiddle.

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

    
31.05.2014 / 04:24