jQuery/Javascript 从对象数组中删除一个对象
jQuery/Javascript removing an object from array of objects
我有一个对象数组,如下所示:
[
[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 的项目保留在数组中...
这里有什么问题吗? :/
您不能将字符串与对象进行匹配。像下面这样使用 findIndex 并使用返回的索引。
function remove(array, element) {
const index = array.findIndex(e => e.asin === element);
array.splice(index, 1);
console.log("Removed element: " + element);
}
您可能想将删除功能扩展到:
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");
尝试以下操作:
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);
我有一个对象数组,如下所示:
[
[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 的项目保留在数组中...
这里有什么问题吗? :/
您不能将字符串与对象进行匹配。像下面这样使用 findIndex 并使用返回的索引。
function remove(array, element) {
const index = array.findIndex(e => e.asin === element);
array.splice(index, 1);
console.log("Removed element: " + element);
}
您可能想将删除功能扩展到:
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");
尝试以下操作:
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);