我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?
当前回答
好像这个问题还没有被打得稀烂似的……
这里有一个,不管它给你带来了什么好奇心……
如果你确定你的对象将只有字符串值,你可能真的会用尽自己来想象这个实现:
var o = { a: '_A', b: '_B', c: '_C' }
, json = JSON.stringify(o)
, split = json.split('')
, nosj = split.reverse()
, o2 = nosj.join('');
var reversed = o2.replace(/[{}]+/g, function ($1) { return ({ '{':'}', '}':'{' })[$1]; })
, object = JSON.parse(reversed)
, value = '_B'
, eulav = value.split('').reverse().join('');
console.log('>>', object[eulav]);
也许这里有一些有用的东西……
希望这能让你开心。
其他回答
保持原型干净。
function val2key(val,array){
for (var key in array) {
if(array[key] == val){
return key;
}
}
return false;
}
例子:
var map = {"first" : 1, "second" : 2};
var key = val2key(2,map); /*returns "second"*/
我通常推荐lodash而不是underscore。
如果你有,就好好利用。
如果没有,那么应该考虑使用lodash。反转NPM包,它非常小。
下面是如何使用gulp测试它:
1)创建一个名为gulpfile.js的文件,包含以下内容:
// Filename: gulpfile.js
var gulp = require('gulp');
var invert = require('lodash.invert');
gulp.task('test-invert', function () {
var hash = {
foo: 1,
bar: 2
};
var val = 1;
var key = (invert(hash))[val]; // << Here's where we call invert!
console.log('key for val(' + val + '):', key);
});
2)安装lodash。倒转包装,大口吞咽
$ npm i --save lodash.invert && npm install gulp
3)测试它是否有效:
$ gulp test-invert
[17:17:23] Using gulpfile ~/dev/npm/lodash-invert/gulpfile.js
[17:17:23] Starting 'test-invert'...
key for val(1): foo
[17:17:23] Finished 'test-invert' after 511 μs
参考文献
https://www.npmjs.com/package/lodash.invert
https://lodash.com/
lodash和underscore的区别
https://github.com/gulpjs/gulp
没有可用的标准方法。你需要迭代,你可以创建一个简单的helper:
Object.prototype.getKeyByValue = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
var test = {
key1: 42,
key2: 'foo'
};
test.getKeyByValue( 42 ); // returns 'key1'
提醒一句:即使上述方法有效,扩展任何主机或本机对象的.prototype通常也不是一个好主意。我这样做是因为它很适合这个问题。不管怎样,你应该在.prototype之外使用这个函数,并将对象传递给它。
或者,更简单的是—按您想要的顺序创建一个具有键和值的新对象,然后查找该对象。我们在使用上面的原型代码时发生了冲突。你不必在键周围使用String函数,那是可选的。
newLookUpObj = {};
$.each(oldLookUpObj,function(key,value){
newLookUpObj[value] = String(key);
});
给定输入={"a":"x", "b":"y", "c":"x"}…
使用第一个值(如输出={“x”:“一”,“y”:“b”}):
输入= { “一个”:“x”, “b”:“y”, “c”:“x” } output = Object.keys(input)。reduceRight(函数(accum, key, i) { Accum [input[key]] = key; 返回accum; }, {}) console.log(输出)
使用最后一个值(例如输出={“x”:“c”、“y”:“b”}):
输入= { “一个”:“x”, “b”:“y”, “c”:“x” } output = Object.keys(input)。Reduce(函数(accum, key, i) { Accum [input[key]] = key; 返回accum; }, {}) console.log(输出)
为每个值数组的键(例如输出={“x”:“c”,“a”,“y”:[b]}):
输入= { “一个”:“x”, “b”:“y”, “c”:“x” } output = Object.keys(input)。reduceRight(函数(accum, key, i) { accum[输入[主要]]= (accum[输入[键 ]] || []). concat(关键); 返回accum; }, {}) console.log(输出)