简体   繁体   English

通过键访问JavaScript对象

[英]Accessing JavaScript object via key

I have a JavaScript object called data. 我有一个名为data的JavaScript对象。 I am using the following code to sort the keys in the object : 我正在使用以下代码对对象中的键进行排序:

var index = [];

// build the index
for (var x in data) {
    index.push(x);
}

// sort the index
index.sort(function (a, b) {
    return a == b ? 0 : (a > b ? 1 : -1);
});

I then want to access the value for a particular index key in the following way : 然后,我想通过以下方式访问特定索引键的值:

for (var i=0; i<index.length; i++) {
    var key = index[i];
    document.getElementById(key).value = data.key;
}

However I am getting undefined for the data.key value. 但是我对data.key值未定义。 Can anyone suggest why ? 有人可以建议原因吗?

Change to 改成

document.getElementById(key).value = data[key];

If the key you want to access is stored within a variable, you have to use the bracket notation. 如果要访问的密钥存储在变量中,则必须使用括号表示法。 In your code, JavaScript will search for a key named "key" and thus fails. 在您的代码中,JavaScript将搜索名为“ key”的键,因此失败。

Example: 例:

var key = 'test';

console.log( data.key );  // yields content of data.key
console.log( data[key] ); // yields content of data.test

How about 怎么样

Object.keys(data)[key] ?

Not sure it would work, without showing the structure of data. 如果不显示数据结构,不确定它是否可以工作。

edit: This way retrieves object key according to numerical index (0,1...,n), and not by name. 编辑:这种方式根据数字索引(0,1 ...,n)而不是名称来检索对象键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM