如何在Firestore中存储二叉树节点 [英] How store binary tree nodes in firestore
问题描述
我想在react中创建一个二叉树.我正在使用 react-d3-tree 组件来显示树. 对于 react-d3-tree ,数据的格式应为
I want to create a binary tree in react.I am using react-d3-tree component for displaying the tree. For react-d3-tree the data should be of the format
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上存储数据,以便我可以将其检索为上述数组格式?
How to store data on firestore so that I can retrieve it and get it as the above array format?
推荐答案
您只需传递封装在对象中的myTreeData
变量,如下所示:
You just have to pass your myTreeData
variable encapsulated in an object, as follows:
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)
The above code saves the {tree: myTreeData}
object in a Firestore document and gets back this document in order to log the value of the tree
field in the console (as a JavaScript Object and as a JSON)
这篇关于如何在Firestore中存储二叉树节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!