1

How to delete object from array field by array index? or suggest another way!

i want to choose object from files array and delete! enter image description here

1 Answer 1

1

There is no choose and delete method from an array in cloud firestore. What you can do is get that array to a temporary array and remove the object that you need to delete from the array and overwrite the document array field with your newly updated temporary array.

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);
    }
}
        
Sign up to request clarification or add additional context in comments.

2 Comments

Now i got another problem, i realise that delete by index bad idea, cause index will change anyway after removal, maybe possible somehow find by some keyword inside array and delete whole array element?
yes @AwKingOftheworld, you can. You can use filter method of array to filter out the array which do not have that finding key. tempArr = tempArr.filter(e => e.attributeName != findingKeyword)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.