【问题标题】:firebase delete object from field array by indexfirebase 按索引从字段数组中删除对象
【发布时间】:2021-06-06 19:35:06
【问题描述】:

如何通过数组索引从数组字段中删除对象?或建议其他方式!

我想从文件数组中选择对象并删除!

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    云 Firestore 中的数组中没有 choose and delete 方法。您可以做的是将该数组放入一个临时数组,然后从数组中删除您需要删除的对象,并用您新更新的临时数组覆盖文档array field。

    const deleteObjFromArr = async (index) => {
        try {
            /*
             * Get the files array to a temporary array.
             * If you have already gotten the document to an object,
             * assign the object field to the temporary array
             */
            
            const docRef = firebase.firestore().collection('tasks-collection').doc('tasks');
            const tempArr = (await docRef.get()).files;
            
            // Remove object from array
            tempArr.splice(index, 1);
            
            // Save new array in cloud firestore
            await docRef.update({ files: tempArr });
            console.log('Files array updated successfully');
            
        } catch (err) {
            console.log('Error occured. Operation terminated.');
            console.log(err);
        }
    }
            
    

    【讨论】:

    • 现在我遇到了另一个问题,我意识到按索引删除是个坏主意,因为删除后索引无论如何都会改变,也许可以通过数组中的某个关键字找到并删除整个数组元素?
    • 是的@AwKingOftheworld,你可以。您可以使用数组的filter 方法过滤掉没有该查找键的数组。 tempArr = tempArr.filter(e => e.attributeName != findingKeyword)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2014-12-10
    相关资源
    最近更新 更多