我有一个非常简单的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]);

也许这里有一些有用的东西……

希望这能让你开心。

其他回答

没有可用的标准方法。你需要迭代,你可以创建一个简单的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}); //→'鹅卵石'

我们可以使用简单的函数来获取传递的值

const getKeyByValue = (object, value) => Object.keys(object).find(key => object[key] === value)

这里有一个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>

保持简单!

你不需要通过复杂的方法或库来过滤对象,Javascript有一个内置的名为object .values的函数。

例子:

let myObj = {jhon: {age: 20, job: 'Developer'}, marie: {age: 20, job: 
'Developer'}};

function giveMeTheObjectData(object, property) {
   return Object.values(object[property]);
}

giveMeTheObjectData(myObj, 'marie'); // => returns marie: {}

这将返回对象属性数据。

参考文献

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/values