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


当前回答

没有看到以下内容:

Const obj = { id: 1、 名称:“窝” }; 函数getKeyByValue(obj, value) { 返回Object.entries (obj)。Find (([, name]) => value === name); } const [key] = getKeyByValue(obj, 'Den'); console.log(关键)

其他回答

保持简单!

你不需要通过复杂的方法或库来过滤对象,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

我通常推荐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

下划线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}

没有可用的标准方法。你需要迭代,你可以创建一个简单的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库,你可以使用_。findKey功能:

var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};

_.findKey(users, function(o) { return o.age < 40; });
// => 'barney' (iteration order is not guaranteed)

// The `_.matches` iteratee shorthand.
_.findKey(users, { 'age': 1, 'active': true });
// => 'pebbles'

// The `_.matchesProperty` iteratee shorthand.
_.findKey(users, ['active', false]);
// => 'fred'

// The `_.property` iteratee shorthand.
_.findKey(users, 'active');
// => 'barney'