-6

I need to find the key of last property starting with a string

JSON:

var data = {
    "admin": "peterson",
    "worker": "peter napier",        
    "housekeeper": "peterson",
    "worker": "richard Ben",
    "executive": "richard parker",
    "executive": "peter alp",
    "housekeeper": "richard johny",
    "admin": "richardson"
};

I have to write an algorithm which will return the key corresponding to the last occurence of value starting with a string.

Ex: I need to get admin if I call findKey("richard") I need to get executive if I call findKey("peter")

I have iterated the object using simple for loop as this

for (var key in yourobject) {
  console.log(key, yourobject[key]);
}

But I like to know the fastest way of iterating this as my scenario has more than 100000 property.

Khaleel
  • 1,212
  • 2
  • 16
  • 34

2 Answers2

1

Just iterate over your data and store each name beginning with your key :

function findkey(name) {
  var lg = name.length,
      found;

  for(var line in data) {
    if(data[line].length >= lg && data[line].substring(0,lg) === name) {
      found = line; 
    }
  }

  return found;
}
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
1

Here you go

var findKey = function (string) {
    var keyToReturn;
    for(key in data){
        if(data[key].indexOf(string) === 0)
            keyToReturn = key;
    }
    return keyToReturn;
}
Mritunjay
  • 25,338
  • 7
  • 55
  • 68