[英]Firebase - How can I save each object item by a child slug, opposed to their index number?
How can I save items in an object as there nested tag (as apposed to there index number). 如何将对象中的项目保存为嵌套标签(与索引编号相对应)。
For instance Im working with the follow data: 例如,我正在使用以下数据:
{
"all_items": [
{
"id": 900,
"item_id": 20,
"name": "First Item",
"slug": "first-item"
},
{
"id": 800,
"item_id": 21,
"name": "Second Item",
"slug": "second-item"
}
]
}
saving it like so: 像这样保存它:
var dataRef = new Firebase("https://<firebase-Id>.firebaseio.com/");
var data= {"all_items": [....]}; // This is the truncated object above.
dataRef.update(data); //saving
In firebase it saves each value by their index as seen here: 在firebase中,它按其索引保存每个值,如下所示:
How can I have the first item the 0 to be saved as its items slug first-item 我怎样才能将第一个项目0保存为它的第一个项目
and the second item (index number 1 ) to save as second-item , and so on. 第二个项目(索引号1 )另存为第二个项目 ,依此类推。
So far I've worked with snapshots like so: 到目前为止,我已经使用过类似的快照:
dataRef.child('all_items')once("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
//KEY
var key = childSnapshot.key();
console.log('key: ', key); // returns 0 then 1
//VALUE
var childData = childSnapshot.val();
console.log('childData: ', childData); //returns first item then second
console.log('slug: ', childData.slug);//returns 'first-item' then 'second-item'
//issue is here. I would like to use
key.update(childData.slug)
//but firebase returns "TypeError: key.update is not a function
});
Now that I can log them, how can I save them where I overwrite the index number by its slug? 现在可以登录它们了,如何将它们保存到被索引段覆盖的索引号中?
I did so by creating a new instance of the firebase reference inside a loop assigning the path for each to is slug: 我是通过在循环内创建一个新的firebase引用实例来实现的,该循环为每个to分配了一条路径。
for (var i in data.all_items) {
singleObj = data.all_items[i];
console.log('one item:',singleObj);
var newDataRef = new Firebase("https://<firebase-id>.firebaseio.com/all_items/"+ val.slug+'/');
newDataRef.update(singleObj)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.