我有一个包含键值对的数组。
var array=[
{Key:"Name",Value:"Sam" },
{Key:"Marks",Value:"50"},
{Key:"Subject",Value:"English"},
];
我想将 Key
为“Subject”的对象的 Value
推送到变量中。我试图了解如何访问 Value,但第一步就失败了。
如何才能做到这一点?
for (var key in array[0])
{
console.log(key[i].Value); //error: Cannot read property 'Value' of undefined
}
如何将 Key
为“Subject”的对象的 Value
插入变量?
最佳答案
您的 for-in
循环位于 array[0]
对象上,因此 key
是该对象的键(属性名称) 。所以这个:
console.log(key[i].Value);
应该是
console.log(array[0][key].Value);
但是,考虑到您所说的您想要做的事情,我认为不需要 for-in
循环:
I want to push Value of object whose Key is 'Subject' into a variable.
Array#find
(这是 ES2015 中的新功能——又名 ES6——但很容易填充/填充)对此很有用:
var entry = array.find(function(e) { return e.Key === "Subject"; });
if (entry) {
theVariable = entry.Value;
}
如果您使用的是 ES2015(目前仍然意味着转译),您可以使用箭头函数来更加简洁:
let entry = array.find(e => e.Key === "Subject");
if (entry) {
theVariable = entry.Value;
}
但是如果你想坚持 ES5 及更早版本中的内容,可以使用 Array#some
:
array.some(function(e) {
if (e.Key === "Subject") {
theVariable = e.Value;
return true; // stops the "loop"
}
});
关于jquery - 从键值数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41461762/