Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

javascript - 获取对象的属性名称(Getting the object's property name)

I was wondering if there was any way in JavaScript to loop through an object like so.

(我想知道JavaScript中是否有任何方法可以像这样遍历一个对象。)

for(var i in myObject) {
    // ...
}

But get the name of each property like this.

(但是这样获取每个属性的名称。)

for(var i in myObject) {
    separateObj[myObject[i].name] = myObject[i];
}

I can't seem to find anything like it on Google.

(我似乎在Google上找不到类似的东西。)

They say to pass the names of the variables with them but this is not an option for what I am trying to achieve.

(他们说与他们一起传递变量的名称,但这不是我想要实现的选择。)

Thanks for any help you can offer.

(谢谢你的尽心帮助。)

  ask by Olical translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

i is the name.

(i是名字。)

for(var name in obj) {
    alert(name);
    var value = obj[name];
    alert(value);
}

So you could do:

(因此,您可以执行以下操作:)

seperateObj[i] = myObject[i];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...