我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?


当前回答

我创建了bimap库(https://github.com/alethes/bimap),它实现了一个强大、灵活和高效的JavaScript双向地图接口。它没有依赖关系,在服务器端(在Node.js中,你可以用npm install bimap安装它)和浏览器中(通过链接到lib/bimap.js)都可以使用。

基本操作非常简单:

var bimap = new BiMap;
bimap.push("k", "v");
bimap.key("k") // => "v"
bimap.val("v") // => "k"

bimap.push("UK", ["London", "Manchester"]);
bimap.key("UK"); // => ["London", "Manchester"]
bimap.val("London"); // => "UK"
bimap.val("Manchester"); // => "UK"

在两个方向上,键值映射的检索同样快。底层没有昂贵的对象/数组遍历,因此无论数据大小如何,平均访问时间都保持不变。

其他回答

给定输入={"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(输出)

没有可用的标准方法。你需要迭代,你可以创建一个简单的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之外使用这个函数,并将对象传递给它。

lodash way https://lodash.com/docs#findKey

Var用户= { 'barney':{'年龄':36,'活跃':true}, 'fred': {'age': 40, 'active': false}, '鹅卵石':{'年龄':1,'活动':true} }; _。findKey(users, {'age': 1, 'active': true}); //→'鹅卵石'

这里有一个Lodash解决方案,适用于flat key =>值对象,而不是嵌套对象。已接受的答案建议使用_。findKey适用于具有嵌套对象的对象,但在这种常见情况下不起作用。

这种方法将对象颠倒,将键交换为值,然后通过查找新(颠倒的)对象上的值来查找键。如果没有找到键,则返回false,我更喜欢undefined,但你可以很容易地在_的第三个参数中交换它。getKey()中的get方法。

// Get an object's key by value var getKey = function( obj, value ) { var inverse = _.invert( obj ); return _.get( inverse, value, false ); }; // US states used as an example var states = { "AL": "Alabama", "AK": "Alaska", "AS": "American Samoa", "AZ": "Arizona", "AR": "Arkansas", "CA": "California", "CO": "Colorado", "CT": "Connecticut", "DE": "Delaware", "DC": "District Of Columbia", "FM": "Federated States Of Micronesia", "FL": "Florida", "GA": "Georgia", "GU": "Guam", "HI": "Hawaii", "ID": "Idaho", "IL": "Illinois", "IN": "Indiana", "IA": "Iowa", "KS": "Kansas", "KY": "Kentucky", "LA": "Louisiana", "ME": "Maine", "MH": "Marshall Islands", "MD": "Maryland", "MA": "Massachusetts", "MI": "Michigan", "MN": "Minnesota", "MS": "Mississippi", "MO": "Missouri", "MT": "Montana", "NE": "Nebraska", "NV": "Nevada", "NH": "New Hampshire", "NJ": "New Jersey", "NM": "New Mexico", "NY": "New York", "NC": "North Carolina", "ND": "North Dakota", "MP": "Northern Mariana Islands", "OH": "Ohio", "OK": "Oklahoma", "OR": "Oregon", "PW": "Palau", "PA": "Pennsylvania", "PR": "Puerto Rico", "RI": "Rhode Island", "SC": "South Carolina", "SD": "South Dakota", "TN": "Tennessee", "TX": "Texas", "UT": "Utah", "VT": "Vermont", "VI": "Virgin Islands", "VA": "Virginia", "WA": "Washington", "WV": "West Virginia", "WI": "Wisconsin", "WY": "Wyoming" }; console.log( 'The key for "Massachusetts" is "' + getKey( states, 'Massachusetts' ) + '"' ); <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

下划线js解决方案

let samplLst = [{id:1,title:Lorem},{id:2,title:Ipsum}]
let sampleKey = _.findLastIndex(samplLst,{_id:2});
//result would be 1
console.log(samplLst[sampleKey])
//output - {id:2,title:Ipsum}