簡體   English   中英

從本地存儲javascript中的對象數組中刪除對象

[英]delete an object from an array of objects in local storage javascript

我在本地存儲中有一個對象數組,如下所示:

ios = [{
    "id" : 1,
    "type" : "in",
    "cat" : "Diversi",
    "qty" : 50,
    "date" : "2016-11-02T09:51:48.872Z",
    "descr" : ""
  }, {
    "id" : 1,
    "type" : "in",
    "cat" : "Lavoro",
    "qty" : 50,
    "date" : "2016-11-02T10:08:11.362Z",
    "descr" : ""
  }];

我想使用此功能刪除對象之一:

function remove(io) {
    var ios = localStorage.getItem('ios') ? JSON.parse(localStorage.getItem('ios')) : [];
    var index;
    for (var i = 0; i < ios.length; i++) {
        if (ios[i] === io) {
          index=i;
          break;
        }
    }
    ios.splice(index, 1);
    localStorage.setItem('ios', JSON.stringify(ios));
}

但是,當我調用該函數並將其參數傳遞給delete時,它不會刪除我想要的那個,而是刪除本地存儲中的第一個。 誰能幫我嗎?

您不能使用===測試2個對象是否相等。 嘗試使用此功能:

function isEquivalent(a, b) {
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    if (aProps.length != bProps.length) {
        return false;
    }

    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        if (a[propName] !== b[propName]) {
            return false;
        }
    }

    return true;
}

而是ios[i] === io ,調用isEquivalent(ios[i],io)

這是因為您的條件永遠不會得到滿足,所以您的索引變量始終是未定義的 ...因此,要么在對象中傳遞一些唯一的鍵值(例如“ id”),然后比較該鍵值對,例如:-

function remove(id) {
    var ios = localStorage.getItem('ios') ? JSON.parse(localStorage.getItem('ios')) : [];
    var index;
    for (var i = 0; i < ios.length; i++) {
        if (ios[i].id === id) {
          index=i;
          break;
        }
    }
    if(index === undefined) return 
    ios.splice(index, 1);
    localStorage.setItem('ios', JSON.stringify(ios));
}

要么

使用LODASH Doc之類的第三方作為:-

function remove(io) {
        var ios = localStorage.getItem('ios') ? JSON.parse(localStorage.getItem('ios')) : [];
        var index;
        index = _.findIndex(ios , io);
        if(index === -1) return 
        ios.splice(index, 1);
        localStorage.setItem('ios', JSON.stringify(ios));
    }

您可以將map功能用作

function removeItem() {    
  var ios = JSON.parse(localStorage.getItem('ios'));
  var index = ios.map(function(element) {
    return element.cat;
  }).indexOf(io.cat);
  ios.splice(index, 1);
  localStorage.setItem('ios', JSON.stringify(ios));
}

根據數組中傳遞的對象的貓刪除項目。 樣品

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM