gpt4 book ai didi

javascript - 循环遍历 droste 效果 javascript 对象

转载 作者:行者123 更新时间:2023-11-30 14:46:41 24 4
gpt4 key购买 nike

我在一个对象的评论中得到了评论中的评论(很像 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
// }
// }
//
}

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

最佳答案

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

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

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

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

关于javascript - 循环遍历 droste 效果 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48802457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com