is it possible to change the key when looping through objects with an external variable. Imagine it like that:
是否可以在使用外部变量循环对象时更改密钥。想象一下:
var data = [{
"id": 1,
"name": "Simon",
"age": 13
}, {
"id": 2,
"name": "Helga",
"age": 18
}, {
"id": 3,
"name": "Tom",
"age": 27
}, ]
var key = name;
for (var i = 0; i < data.length; i++) {
var output = data[i].key;
}
But this, of course, ends up with an undefined output. Goal is to build a function which can handle different loops.
但是,这当然会导致未定义的输出结果。目标是构建一个可以处理不同循环的函数。
2 个解决方案
#1
You can access objects in JavaScript just like you do with arrays. Here is the code you are looking for.
您可以像使用数组一样访问JavaScript中的对象。这是您要寻找的代码。
var data = [{
"id": 1,
"name": "Simon",
"age": 13
}, {
"id": 2,
"name": "Helga",
"age": 18
}, {
"id": 3,
"name": "Tom",
"age": 27
}, ]
var key = "name";
for (var i = 0; i < data.length; i++) {
var output = data[i][key];
}
In reference to the other answer (which appears to have been deleted) I wouldn't recommend using foreach because it is not supported in Internet Explorer 8.
在参考其他答案(似乎已被删除)时,我不建议使用foreach,因为Internet Explorer 8不支持它。
However, you could use:
但是,您可以使用:
var key = "name";
for (var i in data) {
if(data.hasOwnProperty(i))
{
var output = data[i][key];
}
}
#2
I believe you need a function like this:
我相信你需要这样的功能:
function handleKey(objectArray, key) {
for (var index in objectArray) {
//do something with objectArray[index][key]
}
}
Call this function like this: handleKey(data, "name")
像这样调用这个函数:handleKey(data,“name”)
The function handles the key attributes of an object array. You can customize this further based on needs, I decided to be short to keep it simple.
该函数处理对象数组的关键属性。你可以根据需要进一步定制,我决定保持简单。
#1
You can access objects in JavaScript just like you do with arrays. Here is the code you are looking for.
您可以像使用数组一样访问JavaScript中的对象。这是您要寻找的代码。
var data = [{
"id": 1,
"name": "Simon",
"age": 13
}, {
"id": 2,
"name": "Helga",
"age": 18
}, {
"id": 3,
"name": "Tom",
"age": 27
}, ]
var key = "name";
for (var i = 0; i < data.length; i++) {
var output = data[i][key];
}
In reference to the other answer (which appears to have been deleted) I wouldn't recommend using foreach because it is not supported in Internet Explorer 8.
在参考其他答案(似乎已被删除)时,我不建议使用foreach,因为Internet Explorer 8不支持它。
However, you could use:
但是,您可以使用:
var key = "name";
for (var i in data) {
if(data.hasOwnProperty(i))
{
var output = data[i][key];
}
}
#2
I believe you need a function like this:
我相信你需要这样的功能:
function handleKey(objectArray, key) {
for (var index in objectArray) {
//do something with objectArray[index][key]
}
}
Call this function like this: handleKey(data, "name")
像这样调用这个函数:handleKey(data,“name”)
The function handles the key attributes of an object array. You can customize this further based on needs, I decided to be short to keep it simple.
该函数处理对象数组的关键属性。你可以根据需要进一步定制,我决定保持简单。