从键值数组中获取值

Fac*_*der 1 arrays jquery key-value

我有一个带有键值对的数组。

var array=[
             {Key:"Name",Value:"Sam" },
             {Key:"Marks",Value:"50"},
             {Key:"Subject",Value:"English"},
          ];
Run Code Online (Sandbox Code Playgroud)

我想将“主题”Value的对象推Key送到变量中。我试图查看如何访问 Value,但在第一步失败。如何才能做到这一点?

for (var key in array[0])
{
    console.log(key[i].Value); //error:  Cannot read property 'Value' of undefined
}
Run Code Online (Sandbox Code Playgroud)

如何将“主题”Value的对象推Key送到变量中?

T.J*_*der 5

您的for-in循环在array[0]对象上,因此该对象key的键(属性名称)也在。所以这:

console.log(key[i].Value);
Run Code Online (Sandbox Code Playgroud)

应该

console.log(array[0][key].Value);
Run Code Online (Sandbox Code Playgroud)

但是,鉴于您所说的您想要做的,我认为不需要for-in循环:

我想将键为“主题”的对象的值推送到变量中。

Array#find (这是 ES2015 中的新功能——又名 ES6——但很容易填充/填充)对此很有用:

var entry = array.find(function(e) { return e.Key === "Subject"; });
if (entry) {
    theVariable = entry.Value;
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 ES2015(目前仍然意味着转译),您可以使用箭头函数来更简洁:

let entry = array.find(e => e.Key === "Subject");
if (entry) {
    theVariable = entry.Value;
}
Run Code Online (Sandbox Code Playgroud)

但是如果你想坚持 ES5 及更早版本的东西,有Array#some

array.some(function(e) {
    if (e.Key === "Subject") {
        theVariable = e.Value;
        return true; // stops the "loop"
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 妈的,你真快。 (2认同)