迭代json对象javascript [英] iterating through json object javascript
问题描述
我正在努力寻找一种以我喜欢的方式迭代这个JSON对象的方法。我在这里只使用Javascript。
I'm having a really hard time trying to find a way to iterate through this JSON object in the way that I'd like. I'm using only Javascript here.
首先,这是对象
{
"dialog":
{
"dialog_trunk_1":{
"message": "This is just a JSON Test"
},
"dialog_trunk_2":{
"message": "and a test of the second message"
},
"dialog_trunk_3":
{
"message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
}
}
}
现在,我是只是尝试通过这个对象的每个dialog_trunk的基本方法。理想情况下,我想循环遍历对象和每个主干,显示它的消息
值。
Right now, I'm just trying basic ways to get through to each dialog_trunk on this object. I ideally want to loop through the object and for each trunk, display it's message
value.
我试过了使用for循环动态生成dialog_trunk的名称/编号,但我无法使用对象名称的字符串访问该对象,因此我不确定从何处开始。
I've tried using a for loop to generate the name/number of the dialog_trunk on the fly, but I can't access the object using a string for the object name so I'm not sure where to go from here.
推荐答案
为此使用 for..in
循环。请务必检查对象是否拥有属性,还是显示所有继承的属性。一个例子是这样的:
You use a for..in
loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:
var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
或者如果您需要递归来遍历所有属性:
Or if you need recursion to walk through all the properties:
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
这篇关于迭代json对象javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!