-5

Here i need get a value from JavaScript object, if the first 8 digits of property is matched with argument.

Here is what I'm tried...

var input = { 4546546512349: {}, 7200000000007: {}, 9399543200000: {} }
function find_key(query){
  $.each(input, function(k, v) {
    if (k.substring(0,8) == query){
      console.log(k);
      return k        
    }  
  });
}
find_key(45465465);

Is there any best solution for this. Thanks in advance.

Jothimani
  • 137
  • 1
  • 10
  • works for me - https://jsfiddle.net/p6vvp0sx/ - have you included jquery in your page? Although of course if you want to return the value not the key, then you need to use `return v` instead. – Rhumborl Mar 07 '16 at 09:51
  • 1
    You should explain what is not working for you. Is the problem that `console.log(k);` won't display the the key you are looking for or is you problem that you `return k` won't return something from your `find_key` ? – t.niese Mar 07 '16 at 09:54
  • @Rhumbo returning from the callback does not make much sens here, because it won't have an effect unless it is false. – t.niese Mar 07 '16 at 09:54
  • Possible duplicate of [jQuery function returns undefined on callback](http://stackoverflow.com/questions/25623500/jquery-function-returns-undefined-on-callback) – t.niese Mar 07 '16 at 09:57

2 Answers2

1

A solution with Array#filter(). It returns an array with the matched keys.

function findKey(query) {
    return Object.keys(input).filter(function (k) {
        return k.substring(0, 8) == query;
    });
}

var input = { 4546546512349: {}, 7200000000007: {}, 9399543200000: {} }
document.write('<pre>' + JSON.stringify(findKey(45465465), 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Your code already works, but if you are looking for a more concise solution then

function find_key(input,query)
{ 
   return input[Object.keys(input).filter( function(value){ if (value.indexOf( "45465465" ) == 0) {return value;}})[0]];
} 
var input = { 4546546512349: {}, 7200000000007: {}, 9399543200000: {} };
find_key(input,45465465);

One fundamental change done

  • Input being passed as argument to make it more re-usable
gurvinder372
  • 66,980
  • 10
  • 72
  • 94