温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Firestore bulk add field to array

javascript - Firestore批量添加字段到数组

发布于 2020-03-29 13:15:06

我正在努力向数组中的 map添加字段。我正在尝试将"canAssist": false每个map国家/地区的阵列添加到每个阵列中。

这是我的数据库:

[
  {
    "Afghanistan": {
      "country": "Afghanistan",
      "countryCode": "AF",
      "countryCodeAlt": "AFG",
      "emoji": "????????",
      "packages": [
        {
          "name": "Luxury Couple",
          "cost": "$2000.00",
          // I want to add canAssist:false here!
        },
        {
          "name": "Quick Retreat",
          "cost": "$1000.00",
          // I want to add canAssist:false here!
        }
      ]
    }
  },
  {...}
  {...}
]

这是我尝试过的:

let travelData = database.collection('countries').doc(docName);

travelData.get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(array) {
            packages.map(package => {
                return package.add({
                    canAssist: false
                });
            })
        });
    });

查看更多

查看更多

提问者
aszet
被浏览
35
Juan Vieira 2020-02-03 13:22

您可以使用Object.values()和对象分解来实现此目的。

    const querySnapshot = [
      {
        Afghanistan: {
          country: 'Afghanistan',
          countryCode: 'AF',
          countryCodeAlt: 'AFG',
          emoji: '????????',
          packages: [
            {
              name: 'Luxury Couple',
              cost: '$2000.00',
              // I want to add canAssist:false here!
            },
            {
              name: 'Quick Retreat',
              cost: '$1000.00',
              // I want to add canAssist:false here!
            },
          ],
        },
      },
      {
        ...
      },
      {
        ...
      },
    ];

    const updateSnapshot = (snapshot, newData) => {
      return snapshot.map(countryData => {
        // only one field with the name of the country
        const country = Object.values(countryData)[0];

        let updatedCountry = { ...country };
        const field = country[newData.field];
        if (field) {
          if (typeof field === 'string') {
            updatedCountry[newData.field] = newData.values;
          } else if (Array.isArray(field)) {
            updatedCountry[newData.field] = field.map(data => ({ ...data, ...newData.values }));
          }
        }
        return { [updatedCountry.country]: updatedCountry };
      });
    };

    (() => {
      console.log('Original', JSON.stringify(querySnapshot, null, 4));
      const updatedSnapshot = updateSnapshot(querySnapshot, { field: 'packages', values: { canAssist: false } });
      console.log('Updated', JSON.stringify(updatedSnapshot, null, 4));
      const updatedSnapshot2 = updateSnapshot(querySnapshot, { field: 'emoji', values: '????????' });
      console.log('Spanish!', JSON.stringify(updatedSnapshot2, null, 4));
    })();

当然,您不需要对“ newData”具有这种动态性,我只是添加了,以防您想在数据源的任何字段中玩耍。

发布
问题

分享
好友

手机
浏览

扫码手机浏览