如何遍历所有键&嵌套对象的值? [英] How to iterate through all keys & values of nested object?
问题描述
我正在用javascript开发Web应用程序(在服务器端和客户端).我正在以json的形式来回发送数据,并且我希望能够在另一侧进行解析.问题是我内部有多层嵌套对象,所以这就是我被卡住的地方.例如,我正在发送以下数据:
I am developing a web application in javascript (both on the server and client side). I am sending back and forth data as json, and I want to be able to parse it on the other side. The problem is that I have several levels of nested objects inside, so this is where I am stuck. For example, I am sending the following data:
var data = {};
data.title = "My Title";
data.metric = {
fact : "Malicious code detected",
technique : "XSS"
};
data.subject = {
userType : "ADMIN",
userName : "Jack",
clientNumber : "000",
terminal : "192.168.1.1"
};
data.context = {
environment : {
session : "00",
hostname : "mainServer",
sysType : "production"
},
resource : {
wpt : "DIA",
pid : "1024"
}
};
另一方面,当我收到它时,我只想能够完全遍历该对象并打印其内容.我在stackoverflow上看到了很多类似的问题,但是没有一个有帮助.到目前为止,这是我所做的:
On the other side, when I receive it, I just want to be able to completely loop through this object, and print its contents. I have seen a lot of similar questions on stackoverflow, but none of them have been helpful. Here is what I have done so far:
function display(data) {
var resp = "";
var prop = null;
var dataJSON = JSON.parse(data);
for (prop in dataJSON) {
if (patternJSON.hasOwnProperty(prop)) {
resp += "obj" + "." + prop + " = " + dataJSON[prop] + "\n";
}
}
return resp;
}
但是我不知道如何使它自动更深入,无论级别多少. 有人可以指出我正确的方向吗? 任何帮助将不胜感激! 10倍
But I do not know how to make it automatically go deeper, no matter the number of levels. Can somebody point me to the right direction please? Any help would be greatly appreciated! 10x
推荐答案
定义打印功能
function print(obj, prefix) {
prefix = prefix || 'obj';
return Object.keys(obj).reduce(function(acc, key){
var value = obj[key];
if(typeof value === 'object') {
acc.push.apply(acc, print(value, prefix + '.' + key));
}
else {
acc.push(prefix + '.' + key + ' = ' + value);
}
return acc;
}, []);
}
并像这样print(data).join('\n')
使用它.
"obj.title = My Title
obj.metric.fact = Malicious code detected
obj.metric.technique = XSS
obj.subject.userType = ADMIN
obj.subject.userName = Jack
obj.subject.clientNumber = 000
obj.subject.terminal = 192.168.1.1
obj.context.environment.session = 00
obj.context.environment.hostname = mainServer
obj.context.environment.sysType = production
obj.context.resource.wpt = DIA
obj.context.resource.pid = 1024"
这篇关于如何遍历所有键&嵌套对象的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!