1

我在对象中的评论中的评论中有评论(很像 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,使用它来调用数据库,然后将第三个键/值对添加到评论中。

例如

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
      //    }
      // }
      //
    }

我应该如何循环浏览评论,这样评论中有多少评论并不重要?

4

1 回答 1

2

你需要一个递归函数。像这样的东西应该工作:

您还可以使此功能发挥作用并消除潜在的副作用。

/**
 * 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);

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

于 2018-02-15T08:35:41.477 回答