我的问题是我有一个名为对象的数组,其中有几个对象本身就在一个数组中。如何使用 splice 和 findindex 方法检索它们?目前,使用我当前的代码,当我单击从篮子中删除的任何按钮时,它会从数组中删除最后一个对象。我有另一个 object2,它是一个仅包含 id 的简单数组,并且使用的方法效果很好。我想通过 id 搜索从对象数组中删除一个对象。使用示例 object2 数组,该方法在我的代码中运行良好,但不适用于对象数组,请帮助我。
目的 :
(5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
0: Array(2)
0: {lenses: Array(2), _id: "5be1ed3f1c9d44000030b061", name: "Zurss 50S", price: 49900, description: "Lorem ipsum dolor sit amet, consectetur adipisicin…mpor incididunt ut labore et dolore magna aliqua.", …}
1: "35mm 1.4"
length: 2
__proto__: Array(0)
1: (2) [{…}, "50mm 1.8"]
2: (2) [{…}, "25mm 4.5"]
3: (2) [{…}, "50mm 1.7"]
4: (2) [{…}, "50mm 1.4"]
length: 5
__proto__: Array(0)
object2 :
(5) ["5be1ed3f1c9d44000030b061", "5be1ef211c9d44000030b062", "5be9bc241c9d440000a730e7", "5be9c4471c9d440000a730e8", "5be9c4c71c9d440000a730e9"]
这是我的代码
butonAll[i].addEventListener("click", function (e) {
console.log("supprime moi");
const id = e.target.getAttribute("data-id");
objectJs2.splice(
objectJs2.findIndex((x) => {
return x === id;
}),
1
);
objectJs.splice(
objectJs.findIndex((x) => {
return x === id;
}),
1
);
localStorage.setItem("object", JSON.stringify(objectJs));
localStorage.setItem("id", JSON.stringify(objectJs2));
console.log(id);
console.log(objectJs.length);
console.log(line2);
//location.href = "panier.html";
if (objectJs.length === 0) {
localStorage.removeItem("object");
localStorage.removeItem("id");
}
});