0

I have something like this:

var input = [];
var result = {};
input.push({
                key:  1,
                value: Value
                });
                result[input[0].key] = input[0].value;

If I want to get the value from key i call result[key], but what if I want to get the Key from a certain value? Any ideas?

Stefan Perju
  • 288
  • 6
  • 21

3 Answers3

2

You could create an inverse mapping of values → keys; however, there is no guarantee that the values will be unique (whereas the keys must be), so you could map values → array of keys.

function inverseMap(obj) {
  return Object.keys(obj).reduce(function(memo, key) {
    var val = obj[key];
    if (!memo[val]) { memo[val] = []; }
    memo[val].push(key);
    return memo;
  }, {});
}

var a = {foo:'x', bar:'x', zip:'y'};
var b = inverseMap(a); // => {"x":["foo","bar"],"y":["zip"]}

[Update] If your values are definitely unique then you can simply do this:

function inverseMap(obj) {
  return Object.keys(obj).reduce(function(memo, key) {
    memo[obj[key]] = key;
    return memo;
  }, {});
}

inverseMap({a:1, b:2})); // => {"1":"a","2":"b"}

Of course, these solutions assume that the values are objects whose string representation makes sense (non-complex objects), since JavaScript objects can only use strings as keys.

maerics
  • 151,642
  • 46
  • 269
  • 291
0

A value might have several keys, so I'd recommend iterating over all the keys and adding those that have value into a list.

Do you plan to recurse for complex values?

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

You could use underscore.js's find method...

var key = _.find(result, function(val) {
    return val === 'value';
}).key;

This will search your result for the value and return you the object, then you can grab the key off of it.

Underscore is one of my favorite tools for handling these kinds of things. There's lots of powerful methods in it.

jcreamer898
  • 8,109
  • 5
  • 41
  • 56