Eri*_*ric 53 javascript json object
我正在努力寻找一种以我喜欢的方式迭代这个JSON对象的方法.我在这里只使用Javascript.
首先,这是对象
{
"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."
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我只是尝试基本方法来访问此对象上的每个dialog_trunk.理想情况下,我想循环遍历对象和每个主干,显示它的message值.
我已经尝试使用for循环来动态生成dialog_trunk的名称/编号,但我无法使用对象名称的字符串访问该对象,因此我不确定从何处开始.
Roe*_*den 118
你使用一个for..in循环.请务必检查对象是否拥有属性,还是显示所有继承的属性.一个例子是这样的:
var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要递归来遍历所有属性:
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);
Run Code Online (Sandbox Code Playgroud)
Eri*_*ric 10
我的问题实际上是使用JSON对象而不是实际逻辑问题进行错误规划的问题.根据user2736012的建议,我最终要做的是如下组织对象.
{
"dialog":
{
"trunks":[
{
"trunk_id" : "1",
"message": "This is just a JSON Test"
},
{
"trunk_id" : "2",
"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."
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
那时,我能够根据对象的总数做一个相当简单的for循环.
var totalMessages = Object.keys(messages.dialog.trunks).length;
for ( var i = 0; i < totalMessages; i++)
{
console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
}
Run Code Online (Sandbox Code Playgroud)
但是,我的所有浏览器都不支持获取totalMessages的方法.对于我的项目,它实际上并不重要,但要小心,如果你选择使用类似的东西.
这是我的递归方法:
function visit(object) {
if (isIterable(object)) {
forEachIn(object, function (accessor, child) {
visit(child);
});
}
else {
var value = object;
console.log(value);
}
}
function forEachIn(iterable, functionRef) {
for (var accessor in iterable) {
functionRef(accessor, iterable[accessor]);
}
}
function isIterable(element) {
return isArray(element) || isObject(element);
}
function isArray(element) {
return element.constructor == Array;
}
function isObject(element) {
return element.constructor == Object;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
159722 次 |
| 最近记录: |