Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

json数组根据相同key值合并数组

我有一个这样的数组

[
    {
        "comments_id":?1,
        "comments_content":"xxxxx",
        "hasreply":?0,
        "reply_id":?null,
        "reply_content":?null,
    },
    {
        "comments_id":?2,
        "comments_content":"xxxxx",
        "hasreply":?1,
        "reply_id":?1,
        "reply_content":?"xxxxxxx",
    },
    {
        "comments_id":?2,
        "comments_content":"xxxxx",
        "hasreply":?1,
        "reply_id":?2,
        "reply_content":?"xxxxxxx",
    }
]

向根据相同comments_id,合并数组

[
    {
        "comments_id":?1,
        "comments_content":"xxxxx",
        "replys":[]
    },
    {
        "comments_id":?2,
        "comments_content":"xxxxx",
        "replys":[
            {
                "reply_id",1,
                "reply_content":"xxx"
            },
            {
                "reply_id",2,
                "reply_content":"xxx"
            },``
        ]
     }
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

image.png

[].reduce(({m, replys}, { comments_id, comments_content, hasreply, reply_id, reply_content }) => {
    let comment = m[comments_id]
    if (!comment) {
      comment = m[comments_id] = { comments_id, comments_content, replys: [] };
      replys.push(comment)
    }
    if (hasreply) {
      comment.replys.push({reply_id, reply_content})
    }
    return {m, replys}
}, { m:{}, replys:[] }).replys

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...