gpt4 book ai didi

javascript - 将 Firebase 对象的对象转换为 JavaScript/Typescript 数组

转载 作者:行者123 更新时间:2023-12-03 00:32:46 26 4
gpt4 key购买 nike

我将 Firebase 与 Ionic3/Angular4 应用程序结合使用。

Firebase 实时数据库中的数据如下所示:

database structure

使用下面的 TS 代码,我正在从 Firebase 检索可观察数据...

getDishesCategories(uid: string) {

// 1. Fetch an observable AngularFire database snapshot

const afDishCategoriesList$ = this.database.list<DishCategory>(`/users/${uid}/dishcategories/`).snapshotChanges()

// 2. Map the AF list to an observable list of dish category objects

const dishCategoriesList$ = afDishCategoriesList$.pipe(map(changes => {
return changes.map(c => ({
...c.payload.val()
}))
}))

// 3. return the observable list of dish objects

return dishCategoriesList$
}

这给了我以下内容:

[{
createdDate: "2018-12-14T15:59:25.345Z",
dishes: { ozvawkfci1dadyuibgdy4: {name: "Dish 1", selected: true} },
id: "default01",
name: "All Dishes",
selected: true,
toggleDisabled: true
}]

问题在于“菜肴”数据仍以 JSON 形式接收,其中 Firebase 键和值作为对象。

我正在尝试将对象的“dishes”对象映射到标准数组中,这样我就可以在其上调用 .length() 等方法,并使用索引而不是键。

这就是我正在尝试的(菜肴也映射到数组):

[{
createdDate: "2018-12-14T15:59:25.345Z",
dishes: [ {name: "Dish 1", selected: true} ],
id: "default01",
name: "All Dishes",
selected: true,
toggleDisabled: true
}]

我在这里不需要 Firebase 键,只需要一个沼泽标准零索引数组,每个菜肴在每个索引处存储为一个对象。只是无法想象如何做到这一点,因为我是 .map() 的新手,而且我已经盯着它看了几个小时了!

有人可以帮忙吗?

谢谢!

最佳答案

这只是 JavaScript 中的简单数据转换。 Iterate the properties of the objectdishes 中并构建一个仅包含这些属性值的数组。然后用新数组覆盖原始属性。对于数组中的每个对象o,如下所示:

o.dishes = Object.keys(o.dishes).map(key => o.dishes[key])

如果您的目标是较新版本的 JavaScript,则可以使用 o.dishes = Object.values(o.dishes) 更轻松地完成此操作。

关于javascript - 将 Firebase 对象的对象转换为 JavaScript/Typescript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53786327/

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