循环 droste 效果 javascript 对象

Looping through a droste effect javascript Object

我在一个对象的评论中得到了评论中的评论(很像 droste 效果)。对于每个评论,都需要执行特定的操作。评论可以无限期地继续下去。我应该如何遍历它们?

例如

Comments
    randcomment1
        text: "Not important"
        uid: 1234
        Comments
            randsubcomment1
                text: "again ni"
                uid: 5346
            randsubcomment2
                text: "ni"
                uid: 9087
    randcomment2
        text: "N.I"
        uid: 4567

我需要获取每条评论的 uid,使用它来调用数据库,然后将第三对 key/value 添加到评论中。

例如

inidviualcomment
    text: "ni"
    uid: 4567
    nickname: "Mr example" <------ this one should be added based on the uid

我目前拥有的

//  using firebase and vuejs, not relevant
for (let key in val){
      db.ref("users/" + val[key].uid).once("value").then(function(snapshot){
        let value = snapshot.val()
        let nickName = value.nickname
        this.$set(val[key], "nickName", nickName)
      }.bind(this))
      // 
      // here you could add 
      // if (typeod val[key][Comments] != "undefined"){
      //     for (key in val[key][comments]){
      //        and so on, but this is not sustainable
      //    }
      // }
      //
    }

我应该如何遍历评论,使得评论中有多少条评论无关紧要?

你需要一个递归函数。这样的事情应该有效:

您也可以使它起作用并消除潜在的副作用。

/**
 * First function: get all uids
 * @param {array} uids
 * @param {object} comments
 * @returns {void}
 */
function addUids(uids, comments) {
    comments.forEach(function(comment){
        if (uids.indexOf(comment.uid) === -1) {
            uids.push(comment.uid);
        }
        if (typeof comment.comments !== "undefined") {
            addUids(uids, comment.comments);
        }
    });
}

/**
 * Second function: transform comments storage and add nicknames
 * @param {object} nicknames
 * @param {object} comments
 * @returns {void}
 */
function addNicknames(nicknames, comments) {
    comments.forEach(function(comment){
        comment.nickname = nicknames[comment.uid] || null;
        if (typeof comment.comments !== "undefined") {
            addNicknames(nicknames, comment.comments);
        }
    });
}

var uids = [];
addUids(uids, allComments);

// fetch nicknames - make some ajax call (fetch) and return something like:
var nicknames = {"uid1": "nickname1", "uid2": "nickname2"};
addNicknames(nicknames, allComments);

(抱歉,我没有测试代码,你必须自己做,我想你会明白递归函数的概念,我现在没有那么多时间)