循环浏览和删除对象数组中的元素



在我的Vue.js项目中,我有一个对象数组,我想列出这些对象并在浏览器中显示。我的数组包含四个对象,我只想显示三个。我选择这3个对象的方式取决于用户在项目中其他地方选择的首选项设置,并存储在变量中(下面称为userPreference(。我目前一直在寻找基于userPreference值从数组中删除其中一个对象的最佳和最有效的方法。

我的模板中的我的v-for

<ul v-for="item in getOutroItems"><li>item<li></ul>

我的目标:

data() {
return {
outroItems: [{ title: "outro1", text: "XYZ" }, { title: "outro2", text: "ABC" }, { title: "outro3", 
text`enter code here`: "QRS" }, { title: "outro4", text: "TUV" }],
userPreference: ""
};

}

我的计算财产(这是我目前所拥有的(

getOutroItems() { 
this.outroItems.filter((value) => {
if(this.userPreference === "newsletter") {
/// here I want to remove outro2 from my array and return an array with the other 3 values
} else (this.userPreference === "noNewsletter") {
/// here I want to remove outro3 from my array and return an array with the other 3 values
}
})
}

那么,从数组中删除特定元素的最佳方法是什么呢?

提前谢谢,如果有什么不够清楚的地方,请告诉我。

您的需求可以通过以下代码作为array.filter来满足。filter只想在返回中使用true或false来接受或从其数组中删除元素。

getOutroItems() { 
this.outroItems.filter((value) => {
if(this.userPreference === "newsletter") {
// here I want to remove outro2 from my array and return an array with the other 3 values
return value.title != 'outro2';
} else (this.userPreference === "noNewsletter") {
// here I want to remove outro3 from my array and return an array with the other 3 values
return value.title != 'outro3';
}
})
}

但是,如果您不想创建另一个数组(如果它很大(。您应该使用数组中的结束索引元素来交换要删除的这些元素,并从数组中弹出这些元素。

有多种方法可以从数组中获得正确的项。

我的首选方法和您的示例:使用array.filter

const outroItems = [
{ title: "outro1", text: "XYZ" },
{ title: "outro2", text: "ABC" },
{ title: "outro3", text: "QRS" },
{ title: "outro4", text: "TUV" }
];
const leftOverItems = outroItems.filter((item) => item.title !== "outro2");
console.log(leftOverItems);

另一种选择是找到要删除的项目的索引,然后使用splice将其删除

const outroItems = [
{ title: "outro1", text: "XYZ" },
{ title: "outro2", text: "ABC" },
{ title: "outro3", text: "QRS" },
{ title: "outro4", text: "TUV" }
];
const itemToDelete = outroItems.find((item) => item.title === "outro2");
const indexToDelete = outroItems.indexOf(itemToDelete);
outroItems.splice(indexToDelete, 1);
console.log(outroItems);

将上面的任何一个函数与一个函数结合使用,都可以防止编写重复的代码。

const itemToRemove = (arr, attr, name) => {
return arr.filter((item) => item[attr] !== name);
}
const outroItems = [
{ title: "outro1", text: "XYZ" },
{ title: "outro2", text: "ABC" },
{ title: "outro3", text: "QRS" },
{ title: "outro4", text: "TUV" }
];
// Remove from "outroItems" where "title" is "outro2"
const removed2 = itemToRemove(outroItems, "title", "outro2");
// Remove from "outroItems" where "title" is "outro3"
const removed3 = itemToRemove(outroItems, "title", "outro3");
// Remove from "outroItems" where "text" is "TUV"
const removedTUV = itemToRemove(outroItems, "text", "TUV");
console.log(removed2);
console.log(removed3);
console.log(removedTUV);

最新更新