jQuery / Javascript从对象数组中删除对象[重复]

问题描述 投票:0回答:3

这个问题在这里已有答案:

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

[
[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的项目保留在数组中...

这可能有什么问题? :/

javascript jquery arrays multidimensional-array removeall
3个回答
1
投票

您无法将字符串与对象匹配。使用如下所示的findIndex并使用返回的索引。

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

0
投票

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

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

0
投票

请尝试以下方法:

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);
© www.soinside.com 2019 - 2024. All rights reserved.