node.js - 更新 Firestore 文档中嵌套数组对象内的数组
问题描述
我有一个具有以下结构的 Firestore 文档数据,如下所示。我想更新“arrayInsideArray”中的特定对象而不更改其中其他对象的索引。例如,如果我想用“name = item4”的对象更新“name = item1”的对象,它应该只用“name = item4”的对象更新“name = item1”的对象而不改变位置“arrayInsideArray”中的其他对象。我是 NodeJs 和 Typescript 的初学者,我希望有人能帮我解决这个问题。
{
array: [
{
order: 1,
arrayInsideArray:
[ {
id: 1,
name = item1,
...
...
},
{
id: 2,
name = item2,
...
...
},
{
...
...
}
]
},
{
order: 2,
arrayInsideArray:
[ {
id: 3,
name = item3,
...
...
},
{
...
...
}
]
},
{
...
...
}
]
...
}
解决方案
与map
操作员一起做。
如果该物品不是您要找的物品,请按原样退回。否则,执行更改。这将确保相同的顺序。
替换整个项目的示例:
function updateInternalArray(searchedOrder: number, searchedId: number, newItem: any) {
return myData.array.map((item) => {
return item.order === searchedOrder
? { // this is the parent item you want to look at
...item,
arrayInsideArray: item.arrayInsideArray.map((internalItem) => {
return internalItem.id === searchItem
? newItem // this is the internal item you want to update
: internalItem; // this is another internal item, that you want to keep it untouched
})
}
: item; // this a parent item that you want to keep it as it is
})
}
例如,请注意不要覆盖 id。
更新项目的示例:
function updateInternalArray(searchedOrder: number, searchedId: number, newItem: any) {
return myData.array.map((item) => {
return item.order === searchedOrder
? { // this is the parent item you want to look at
...item,
arrayInsideArray: item.arrayInsideArray.map((internalItem) => {
return internalItem.id === searchItem
? {...internalItem, ...newItem} // this is the internal item you want to update
: internalItem; // this is another internal item, that you want to keep it untouched
})
}
: item; // this a parent item that you want to keep it as it is
})
}
推荐阅读
- amazon-web-services - EMR stuck at bootstrap script
- javascript - 为什么我的所有首字母大写的函数在与最终结果比较时返回 false?Javascript
- matplotlib - i am receiving an error when trying to install plotly in jupyter notebook
- android - How to pass the correct coroutine scope in unit test when testing viewmodel
- c# - Entity Framework Property HasConversion with Arguments
- javascript - Bootstrap vue b-modal 在提交数据时不突出显示字段
- java - 将决策参数传递给 @TestConfiguration 类
- android - 在某些设备上完成 Android 的应用内灵活更新过程后,应用不会自动重启
- sql - 如何提取自上一小时以来创建或修改的行
- c++ - 这个“数组中的最大最小元素”逻辑有什么问题?