简体   繁体   中英

How to delete an array from object?

I've got an object of type : [ {name : 'xxx' , price: '555', quantity : '2' } , {...} ] and so one. I got a class

 getCartItems() {
        let items = localStorage.getItem('item');
        items = JSON.parse(items);
        return items;
    }

where i get this array. Now i am getting index of the array, for example 0 , it should remove first array from object. but when i do .remove, or other, it does not work. this.getCartItems()[index].remove or other does not work. Can you help me?

My guess is that you are mutating the object after you parse it and you never save it back.

You have to save the mutated object inside of your localStorage to make your removal of the first item persistant.

Look at the following example :

 const localStorage = { items: { item: JSON.stringify([{ name: 'xxx', price: '555', quantity: '2', }, { name: 'yyy', price: '666', quantity: '5', }, { name: 'zzz', price: '777', quantity: '6', }]), }, getItem: str => localStorage.items[str], setItem: (str, value) => { localStorage.items[str] = value; }, }; function getCartItems() { const items = localStorage.getItem('item'); const parsedItems = JSON.parse(items); // We remove the first element const item = parsedItems.splice(0, 1); // We save the value localStorage.setItem('item', JSON.stringify(parsedItems)); return item; } console.log('First call ---'); console.log(getCartItems()); console.log(''); console.log('Second call ---'); console.log(getCartItems()); console.log(''); console.log('Third call ---'); console.log(getCartItems());

Use filter to get required items. In the following updated will not have earlier 0 index item. Now, the updated array you may want to set in localStorage again if required.

const items = getCartItems();
const indexToRemove = 0;

const updated = items.filter((,index) => index !== indexToRemove);

You can use array method filter to remove the object from array. This can look something like this:

     getCartItems() {
        let items = localStorage.getItem('item');
        items = JSON.parse(items);
        return items;
    }
    removeCart(){
    return id; // the id that you will have from your a tag
    }
const updatedItems = this.getCartItems().filter((item,index) => index !== this.removeCart()); // in updated items you will find your filtered out array of object 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM