[英]Remove values in nested array of objects based on values from another array
I have an array of objects with the following structure:我有一个具有以下结构的对象数组:
let optionList = [
{
images: [
{
url: "test1"
},
{
url: "test2"
}
]
},
{
images: [
{
url: "test3"
},
{
url: "test4"
}
]
},
{
images: [
{
url: "test5"
},
{
url: "test6"
}
]
}
];
I also have another array called imagesToDelete with the following values:我还有另一个名为 imagesToDelete 的数组,其值如下:
let imagesToDelete = ["test1", "test3", "test6"];
My goal is to remove values from the nested array based on the values in the imagesToDelete array.我的目标是根据imagesToDelete数组中的值从嵌套数组中删除值。 If done correctly, this will be the following result:
如果操作正确,这将是以下结果:
let optionList = [
{
images: [
{
url: "test2"
}
]
},
{
images: [
{
url: "test4"
}
]
},
{
images: [
{
url: "test5"
}
]
}
];
Below is my current code which did not remove any values:下面是我当前的代码,它没有删除任何值:
optionList.filter(ol => {
let result = !ol.images.some(
image => image.url === imagesToDelete.includes(image.url)
);
return result;
});
console.log(optionList);
let optionList = [{ images: [{ url: "test1" }, { url: "test2" } ] }, { images: [{ url: "test3" }, { url: "test4" } ] }, { images: [{ url: "test5" }, { url: "test6" } ] } ]; let imagesToDelete = ["test1", "test3", "test6"]; let newOptionList = optionList.map(function(option) { option.images = option.images.filter(function(item) { return !imagesToDelete.includes(item.url) }) return option }) console.log('newOptionList', newOptionList)
There are a couple of issues.有几个问题。 Mostly, you never actually modify the images array in your iterations, and filter based on the optionList which isn't actually removing any items (since if there are no images you state it is left as an empty array).
大多数情况下,您从未在迭代中实际修改图像数组,并根据实际上并未删除任何项目的 optionList 进行过滤(因为如果您声明没有图像,它将保留为空数组)。
You need to iterate optionList, and modify the images array based on the list for deletion.需要迭代optionList,根据list修改images数组进行删除。
You can use forEach
for the outer iteration.您可以将
forEach
用于外部迭代。
let optionList = [ { images: [ { url: "test1" }, { url: "test2" } ] }, { images: [ { url: "test3" }, { url: "test4" } ] }, { images: [ { url: "test5" }, { url: "test6" } ] } ]; let imagesToDelete = ["test1", "test3", "test6"]; optionList.forEach(ol => ol.images = ol.images.filter( image => !imagesToDelete.includes(image.url) ) ); console.log(optionList);
filter()
returns a new array and does not mutate original filter()
返回一个新数组并且不会改变原始数组
Try doing尝试做
const newList = optionList.filter(ol => { let result = !ol.images.some( image => image.url === imagesToDelete.includes(image.url) ); return result; }); console.log(newList);
<script> let imagesToDelete = ["test1", "test3", "test6"]; let optionList = [{images: [{url: "test1"},{url: "test2"}]},{images: [{url: "test3"},{url: "test4"}]},{images: [{url: "test5"},{url: "test6"}]}] </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.