gpt4 book ai didi

javascript - 如何在firestore中存储二叉树节点

转载 作者:行者123 更新时间:2023-12-02 22:04:45 25 4
gpt4 key购买 nike

我想在react中创建一个二叉树。我正在使用react-d3-tree组件来显示树。对于react-d3-tree,数据应采用以下格式

const myTreeData = [
{
name: 'Top Level',
attributes: {
keyA: 'val A',
keyB: 'val B',
keyC: 'val C',
},
children: [
{
name: 'Level 2: A',
attributes: {
keyA: 'val A',
keyB: 'val B',
keyC: 'val C',
},
},
{
name: 'Level 2: B',
},
],
},
];

如何将数据存储在 firestore 上,以便我可以检索它并以上述数组格式获取它?

最佳答案

您只需传递封装在对象中的 myTreeData 变量,如下所示:

const db = firebase.firestore();

const myTreeData = [
{
name: 'Top Level',
attributes: {
keyA: 'val A',
keyB: 'val B',
keyC: 'val C',
},
children: [
{
name: 'Level 2: A',
attributes: {
keyA: 'val A',
keyB: 'val B',
keyC: 'val C',
},
},
{
name: 'Level 2: B',
},
],
},
];

db.collection('yourCollection').add({tree: myTreeData})
.then(function(newDocRef) {
return newDocRef.get();
}).then(function(doc) {
console.log("JavaScript Object:", doc.data().tree);
console.log("JSON:", JSON.stringify(doc.data().tree));
}).catch(function(error) {
console.log("Error getting document:", error);
});
<小时/>

上述代码将 {tree: myTreeData} 对象保存在 Firestore 文档中,并取回该文档,以便在控制台中记录 tree 字段的值(作为 JavaScript 对象和 JSON)

关于javascript - 如何在firestore中存储二叉树节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59754992/

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