在json中获取密钥的索引

shr*_*eyj 20 javascript json

我有一个像这样的json:

json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }
Run Code Online (Sandbox Code Playgroud)

现在,我想知道一个密钥的索引,在json中说"key2" - 这是1.有办法吗?

Gow*_*kan 68

它太晚了,但它可能简单而有用

var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };
var keytoFind = "key2";
var index = Object.keys(json).indexOf(keytoFind);
alert(index);
Run Code Online (Sandbox Code Playgroud)


h2o*_*ooo 11

您不需要对象键的数字索引,但许多其他人已告诉您.

这是实际的答案:

var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };

console.log( getObjectKeyIndex(json, 'key2') ); 
// Returns int(1) (or null if the key doesn't exist)

function getObjectKeyIndex(obj, keyToFind) {
    var i = 0, key;

    for (key in obj) {
        if (key == keyToFind) {
            return i;
        }

        i++;
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

虽然您可能只是在搜索我在此函数中使用的相同循环,但您可以浏览该对象:

for (var key in json) {
    console.log(key + ' is ' + json[key]);
}
Run Code Online (Sandbox Code Playgroud)

哪个会输出

key1 is watevr1
key2 is watevr2
key3 is watevr3
Run Code Online (Sandbox Code Playgroud)


小智 10

原则上,寻找密钥的索引是错误的.哈希映射的键是无序的,您永远不应该期望特定的顺序.


Mos*_*rdy 5

您拥有的是一个表示 JSON 序列化 javascript 对象的字符串。在能够循环遍历其属性之前,您需要将其反序列化回一个 javascript 对象。否则,您将遍历此字符串的每个单独字符。

var resultJSON = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
    var result = $.parseJSON(resultJSON);
    $.each(result, function(k, v) {
        //display the key and value pair
        alert(k + ' is ' + v);
    });
Run Code Online (Sandbox Code Playgroud)

或者干脆:

arr.forEach(function (val, index, theArray) {
    //do stuff
});
Run Code Online (Sandbox Code Playgroud)