-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.

4
  • works for me - 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. Commented Mar 7, 2016 at 9: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 ? Commented Mar 7, 2016 at 9:54
  • @Rhumbo returning from the callback does not make much sens here, because it won't have an effect unless it is false. Commented Mar 7, 2016 at 9:54
  • Possible duplicate of jQuery function returns undefined on callback Commented Mar 7, 2016 at 9:57

2 Answers 2

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>');

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.