我有一个具有以下结构的Firestore文档数据,如下所示。我想更新“ arrayInsideArray”内部的特定对象,而不更改其中其他对象的索引。例如,如果我想用“名称= item4”的对象更新“名称= item1”的对象, 它应该只用“名称= item4”对象更新“名称= item1”对象,而不更改“ arrayInsideArray”中其他对象的位置。我是NodeJs和Typescript的初学者,我希望有人帮我解决这个问题。
{
array: [
{
order: 1,
arrayInsideArray:
[ {
id: 1,
name = item1,
...
...
},
{
id: 2,
name = item2,
...
...
},
{
...
...
}
]
},
{
order: 2,
arrayInsideArray:
[ {
id: 3,
name = item3,
...
...
},
{
...
...
}
]
},
{
...
...
}
]
...
}
答案 0 :(得分:0)
使用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
})
}