简体   繁体   English

从键值对中获取键值

[英]Get Key From Value in Key-Value Pair

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? 如果我想从key中获取值,请调用result[key] ,但如果我想从某个值获取Key怎么办? Any ideas? 有任何想法吗?

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. 当然,这些解决方案假设值是字符串表示有意义的对象(非复杂对象),因为JavaScript对象只能使用字符串作为键。

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? 你打算为复杂的价值进行递归吗?

You could use underscore.js's find method... 你可以使用underscore.js的find方法......

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. Underscore是我最喜欢处理这类东西的工具之一。 There's lots of powerful methods in it. 它有很多强大的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM