我有一个可能如下所示的对象:

var nicknames = []
nicknames.push({id:"100", name:"john", id2:"200", name2:"max"});

但对象也可能如下所示:
nicknames.push({id:"200", name:"max", id2:"100", name2:"john"});

所以键和值可能会被切换。

如果提供 "max" 的名称或 "200" 的名称,我怎样才能获得名称和 ID "john"和 "100"?

最佳答案

var found_name, found_id;
for(var i = 0; i < nicknames.length; i++) {
    var nn = nicknames[i];
    if (nn.name == "max" || nn.id = "200") {
        found_name = nn.name2;
        found_id = nn.id2;
        break;
    } else if (nn.name2 == "max" || nn.id2 = "200") {
        found_name = nn.name;
        found_id = nn.id;
        break;
    }
}

关于Javascript从对象中获取对应的键/值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27741114/

10-13 08:05