代码之家  ›  专栏  ›  技术社区  ›  User987

jquery/javascript从对象数组中删除对象[重复]

  •  0
  • User987  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我有一组对象,看起来像这样:

    [
    [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函数:

      remove(items, "1234");
    

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

    这里可能有什么问题?:

    3 回复  |  直到 6 年前
        1
  •  1
  •   baao    6 年前

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

    function remove(array, element) {
        const index = array.findIndex(e => e.asin === element);
        array.splice(index, 1);
        console.log("Removed element: " + element);
    }
    
        2
  •  0
  •   Jonas Wilms    6 年前

    您可以将移除功能扩展到:

    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
  •  0
  •   amrender singh    6 年前

    请尝试以下操作:

    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);