我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?
当前回答
保持简单!
你不需要通过复杂的方法或库来过滤对象,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
其他回答
如果你有一个数组值的对象。这里有一个很好的例子。让我们假设您希望根据所拥有的文件的扩展名显示一个图标。具有相同图标的所有扩展都在相同的对象值下。
注意:将这里的case包装在一个对象中要比使用大量case进行切换要好。
检查下面的代码片段(用es6编写),看看我们如何为特定的扩展返回特定的键。
我从这个git仓库拿到了扩展名列表
// Oject that contains different icons for different extentions const icons = { "music": ["mp3", "m4a", "ogg", "acc", "flac","m3u", "wav"], "video": ["mp4","webm", "mkv", "avi", "mov", "m4v", "mpeg"], "image": ["jpg", "gif", "png", "jpeg", "tif", "psd", "raw", "ico"], "archives": ["zip", "rar", "tar", "dmg", "jar"], "3d-files": ["3ds", "dwg", "obj", "dae", "skp", "fbx"], "text": ["doc", "rtf", "txt", "odt", "tex"], "vector-graphics":["ai", "svg"], "pdf": ["pdf"], "data": ["xml", "csv", "xls"] } const get_icon_Key =( icons_object,file_extention) => { // For each key we chack if the value is contained in the list of values let key = Object.keys(icons_object).find( k=> icons[k].find( // At this leve we check if the extention exist in the array of the specific object value ie. 'music', 'video' ... icons_ext => icons_ext === file_extention) // if we find it means this is the key we are looking for ? true: false); return key } console.log(`The icon of for mp3 extention is: => ${get_icon_Key(icons,"mp3")}`) console.log(`The icon of for mp4 extention is: => ${get_icon_Key(icons,"mp4")}`)
下划线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}
如前所述,迭代是必要的。例如,在现代浏览器中,你可以有:
var key = Object.keys(obj).filter(function(key) {return obj[key] === value})[0];
value包含了你要找的值。 说到这里,我可能会使用循环。
否则,你可以使用一个合适的“hashmap”对象——在JS中有几个实现——或者你自己实现。
更新2018
六年过去了,但我仍然得到了一些投票,所以我觉得一个更现代的解决方案——适用于现代浏览器/环境——应该在答案中提到,而不仅仅是在评论中:
const key = Object.keys(obj).find(key => obj[key] === value);
当然它也可以是一个函数:
const getKeyByValue = (obj, value) =>
Object.keys(obj).find(key => obj[key] === value);
ES6方法:
Object.fromEntries(Object.entries(a).map(b => b.reverse()))['value_you_look_for']
这为我获得对象的键/值工作。
让obj = { “key1”:“value1”, “key2”:“value2”, “key3”:“value3”, “key4”:“value4” } 种(obj) . map函数(k) { Console.log ("key with value: "+k +" = "+obj[k]) })