我想将以下JSON转换为另一种结构。
源JSON:
{
"values": [
{
"action": "COMMENTED",
"comment": {
"text": "comment text",
"comments": [
{
"text": "reply text",
"comments": [],
"tasks": []
}
],
"tasks": [
{
"text": "task text",
"state": "RESOLVED"
}
]
}
}
]
}
目标JSON:
[
{
"text": "comment text",
"children": [
{
"text": "reply text",
"type": "comment"
},
{
"text": "task text",
"state": "RESOLVED"
}
]
}
]
我开始:
data = data.values.filter((e)=>{
return e.action === 'COMMENTED';
}).map((e)=>{
// hmmm recursion needed, how to solve?
});
答案 0 :(得分:3)
data = data.values.filter(e => e.action === 'COMMENTED')
.map(function recursion({comment}){
return {
text: comment.text,
children: [...comment.comments.map(recursion), ...comment.tasks];
};
});
答案 1 :(得分:0)
我最终得到了:
let data = response.data.values
.filter(e => e.action === 'COMMENTED')
.map(function e({comment, commentAnchor}) {
return {
commentAnchor,
text: comment.text,
children: [...comment.comments.map(function recursion(comment) {
if (typeof comment === 'undefined') {
return {};
}
let children = [];
if (comment.comments) {
children.push(...comment.comments.map(recursion));
}
if (comment.tasks) {
children.push(...comment.tasks);
}
let _return = {
...comment,
text: comment.text
};
_return.children = children;
return _return;
}), ...comment.tasks]
}
});