遍历json对象javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19323699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iterating through json object javascript
提问by Eric
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.
我真的很难找到一种方法来以我想要的方式遍历这个 JSON 对象。我在这里只使用 Javascript。
First, here's the object
首先,这是对象
{
"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."
}
}
}
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 messagevalue.
现在,我只是尝试基本方法来访问此对象上的每个 dialog_trunk。理想情况下,我想遍历对象并为每个树干显示它的message值。
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 循环动态生成 dialog_trunk 的名称/编号,但是我无法使用对象名称的字符串访问该对象,所以我不确定从哪里开始。
回答by Hozuki
You use a for..inloop 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:
您for..in为此使用循环。一定要检查对象是否拥有属性或所有继承的属性也显示出来。一个例子是这样的:
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);
回答by Eric
My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.
我的问题实际上是 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."
}
]
}
}
At that point, I was able to do a fairly simple for loop based on the total number of objects.
那时,我能够根据对象总数执行一个相当简单的 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);
}
My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.
但是,并非所有浏览器都支持我获取 totalMessages 的方法。对于我的项目,这实际上并不重要,但是如果您选择使用类似的东西,请注意这一点。
回答by schirrmacher
Here is my recursive approach:
这是我的递归方法:
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;
}
回答by JMerinoH
An improved version for recursive approach suggested by @schirrmacher to print key[value] for the entire object:
@schirrmacher 建议的递归方法的改进版本,用于打印整个对象的 key[value]:
var jDepthLvl = 0;
function visit(object, objectAccessor=null) {
jDepthLvl++;
if (isIterable(object)) {
if(objectAccessor === null) {
console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- START ? ?", "background:yellow");
} else
console.log("%c"+spacesDepth(jDepthLvl)+objectAccessor+"%c:","color:purple;font-weight:bold", "color:black");
forEachIn(object, function (accessor, child) {
visit(child, accessor);
});
} else {
var value = object;
console.log("%c"
+ spacesDepth(jDepthLvl)
+ objectAccessor + "[%c" + value + "%c] "
,"color:blue","color:red","color:blue");
}
if(objectAccessor === null) {
console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- END ? ?", "background:yellow");
}
jDepthLvl--;
}
function spacesDepth(jDepthLvl) {
let jSpc="";
for (let jIter=0; jIter<jDepthLvl-1; jIter++) {
jSpc+="\u0020\u0020"
}
return jSpc;
}
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;
}
visit($OBJECT_OR_ARRAY$);


