我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?
当前回答
给定输入={"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(输出)
其他回答
我通常推荐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
或者,更简单的是—按您想要的顺序创建一个具有键和值的新对象,然后查找该对象。我们在使用上面的原型代码时发生了冲突。你不必在键周围使用String函数,那是可选的。
newLookUpObj = {};
$.each(oldLookUpObj,function(key,value){
newLookUpObj[value] = String(key);
});
使用Underscore.js库:
var hash = {
foo: 1,
bar: 2
};
(_.invert(hash))[1]; // => 'foo'
最短一行
let key = Object.keys(obj).find(k=>obj[k]===value);
返回值为:
let keys = Object.keys(obj).filter(k=>obj[k]===value);
如果value为数组或对象:
let keys = Object.keys(obj).filter(k=>JSON.stringify(obj[k])===JSON.stringify(value));
保持原型干净。
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"*/