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


当前回答

真的很简单。

const CryptoEnum = Object.freeze({
                    "Bitcoin": 0, "Ethereum": 1, 
                    "Filecoin": 2, "Monero": 3, 
                    "EOS": 4, "Cardano": 5, 
                    "NEO": 6, "Dash": 7, 
                    "Zcash": 8, "Decred": 9 
                  });

Object.entries(CryptoEnum)[0][0]
// output => "Bitcoin"

其他回答

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

如果你有一个数组值的对象。这里有一个很好的例子。让我们假设您希望根据所拥有的文件的扩展名显示一个图标。具有相同图标的所有扩展都在相同的对象值下。

注意:将这里的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")}`)

http://jsfiddle.net/rTazZ/2/

var a = new Array(); 
    a.push({"1": "apple", "2": "banana"}); 
    a.push({"3": "coconut", "4": "mango"});

    GetIndexByValue(a, "coconut");

    function GetIndexByValue(arrayName, value) {  
    var keyName = "";
    var index = -1;
    for (var i = 0; i < arrayName.length; i++) { 
       var obj = arrayName[i]; 
            for (var key in obj) {          
                if (obj[key] == value) { 
                    keyName = key; 
                    index = i;
                } 
            } 
        }
        //console.log(index); 
        return index;
    } 

因为这些值是唯一的,所以应该可以将这些值添加为一组额外的键。这可以用下面的快捷方式完成。

var foo = {};
foo[foo.apple = "an apple"] = "apple";
foo[foo.pear = "a pear"] = "pear";

这将允许通过键或值进行检索:

var key = "apple";
var value = "an apple";

console.log(foo[value]); // "apple"
console.log(foo[key]); // "an apple"

这确实假设键和值之间没有公共元素。

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