繁体   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