【问题标题】:jQuery/Javascript removing an object from array of objects [duplicate]jQuery / Javascript从对象数组中删除一个对象[重复]
【发布时间】:2018-11-14 00:53:01
【问题描述】:

我有一个如下所示的对象数组:

[
[0]{"asin": "1234",
    "title: "Test"},
[1] {"asin": "123fef4",
    "title: "aaaaaaa"},
[2] {"asin": "testtet",
     "title: "testt123"},
]

将项目添加到数组中就像一个魅力,这里是代码:

 items.push(
 {
   "asin": "1234",
   "title": "test"
 });

这部分工作正常...现在是我需要通过其中的 ASIN 属性从数组中删除项目的部分...

我有一个看起来像这样的函数:

  function remove(array, element) {
            const index = array.indexOf(element);
            array.splice(index, 1);
            console.log("Removed element: " + element);
        }

我如何调用删除函数:

  remove(items, "1234");

这会从列表中删除项目,但不是我想要的项目。当我传递值 1234 时检查,asin 值为 1234 的项目保留在数组中...

这里可能有什么问题? :/

【问题讨论】:

  • 导致对象与字符串不匹配?!?!?
  • @JonasW。好的,但我该如何解决? :)

标签: javascript jquery arrays multidimensional-array removeall


【解决方案1】:

您不能将字符串与对象匹配。像下面这样使用 findIndex 并使用返回的索引。

function remove(array, element) {
    const index = array.findIndex(e => e.asin === element);
    array.splice(index, 1);
    console.log("Removed element: " + element);
}

【讨论】:

    【解决方案2】:

    您可能希望将删除功能扩展到:

    function remove(array, key, value) {
      const index = array.findIndex(el => (el[key] || el) === value);
            array.splice(index, 1);
            console.log("Removed: " + index);
    }
    

    所以你可以这样做

    remove(items, "asin", "1234");
    

    【讨论】:

      【解决方案3】:

      尝试以下方法:

      var arr =[
      {"asin": "1234",
      "title": "Test"},
      {"asin": "123fef4",
      "title": "aaaaaaa"},
      {"asin": "testtet",
      "title": "testt123"},
      ];
      
      function remove(arr, val){
        var index = arr.findIndex((o)=> o.asin === val);
        if(index != 1)
          arr.splice(index, 1);
      }
      remove(arr, "1234");
      console.log(arr);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-08
        • 1970-01-01
        • 2020-04-15
        • 2018-06-19
        • 2014-06-25
        • 2020-10-25
        • 1970-01-01
        • 2018-08-15
        相关资源
        最近更新 更多