首页 > 解决方案 > firebase 按索引从字段数组中删除对象

问题描述

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

我想从文件数组中选择对象并删除! 在此处输入图像描述

标签: reactjsfirebasegoogle-cloud-firestore

解决方案


choose and deleteCloud Firestore 中的数组没有方法。您可以做的是将该数组放入临时数组,然后从数组中删除您需要删除的对象,并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);
    }
}
        

推荐阅读