首页 > 解决方案 > 更新 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,
                  ...
                  ...
                },
                {
                  ...
                  ...
                }
              ]
          },
          {
            ...
            ...
          }
        ]
          ...
}

标签: node.jstypescriptgoogle-cloud-firestore

解决方案


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
        })
    }

推荐阅读