javascript-分层数据,如何循环所有级别并将附加数据插入每个节点
作者:互联网
我在Javascript中具有分层数据,如下所示,我尝试在每个注释节点中找到添加jsonStringify的方法,该怎么做?
var o = {
"comments": {
"count": 2,
"data": [
{
"text": "..",
"comments": {
"count": 1,
"data": [
{
"text": "..",
"comments": {
"count": 0,
"data": [],
// "jsonStringify":
}
},
],
// "jsonStringify":
}
},
{
"text": "..",
"comments": {
"count": 0,
"data": [],
// "jsonStringify":
}
},
],
// "jsonStringify":
}
};
添加jsonStringfy
这只能在知道多少级的情况下工作
var jsonStringify = JSON.stringify(o.comments);
o.comments.jsonStringify = jsonStringify;
for (var i = 0; i < o.comments.data.length; i++) {
var jsonStringify = JSON.stringify(o.comments.data[i].comments);
o.comments.data[i].comments.jsonStringify = jsonStringify;
}
例如上述数据有2个分支,最深的级别是3(
“评论”> “评论”> “评论”,
“评论”>“评论”),
我想找到每个“注释”,获取类似于1的值,并应用于JSON.stringify函数,获取结果,然后修改同一节点,将结果插入为2
1
"comments": {
"count": 0,
"data": []
}
2
"comments": {
"count": 0,
"data": [],
"jsonStringify": "{\"count\":0,\"data\":[]}"
}
我试图找到方法,如果数据未知多少级别
解决方法:
在修改原始问题之前,已回答了该问题,并注明了不同的计数数字.
仍在等待作者详细说明.
源代码:
var o = {
"comments": {
"count": 2,
"data": [
{
"text": "..",
"comments": {
"count": 1,
"data": [
{
"text": "..",
"comments": {
"count": 0,
"data": [],
}
},
]
}
},
{
"text": "..",
"comments": {
"count": 0,
"data": []
}
}
]
}
};
function jsonStringify(array){
for(var i=0;i<array.length;i++){
var ar = array[i];
ar.comments.jsonStringify = JSON.stringify(ar.comments);
ar.comments.data = jsonStringify(ar.comments.data);
array[i] = ar;
}
return array;
}
var result = jsonStringify([o]);
console.log( JSON.stringify(result,null,'\t') );
结果:
[
{
"comments": {
"count": 2,
"data": [
{
"text": "..",
"comments": {
"count": 1,
"data": [
{
"text": "..",
"comments": {
"count": 0,
"data": [],
"jsonStringify": "{\"count\":0,\"data\":[]}"
}
}
],
"jsonStringify": "{\"count\":1,\"data\":[{\"text\":\"..\",\"comments\":{\"count\":0,\"data\":[]}}]}"
}
},
{
"text": "..",
"comments": {
"count": 0,
"data": [],
"jsonStringify": "{\"count\":0,\"data\":[]}"
}
}
],
"jsonStringify": "{\"count\":2,\"data\":[{\"text\":\"..\",\"comments\":{\"count\":1,\"data\":[{\"text\":\"..\",\"comments\":{\"count\":0,\"data\":[]}}]}},{\"text\":\"..\",\"comments\":{\"count\":0,\"data\":[]}}]}"
}
}
]
标签:loops,hierarchical-data,hierarchy,json,javascript 来源: https://codeday.me/bug/20191027/1944097.html