首页 > 解决方案 > 根据另一个数组中的值删除嵌套对象数组中的值

问题描述

我有一个具有以下结构的对象数组:

let optionList = [
  {
    images: [
      {
        url: "test1"
      },
      {
        url: "test2"
      }
    ]
  },
  {
    images: [
      {
        url: "test3"
      },
      {
        url: "test4"
      }
    ]
  },
  {
    images: [
      {
        url: "test5"
      },
      {
        url: "test6"
      }
    ]
  }
];

我还有另一个名为 imagesToDelete 的数组,具有以下值:

 let imagesToDelete = ["test1", "test3", "test6"];

我的目标是根据imagesToDelete数组中的嵌套数组中删除 值。如果正确完成,这将是以下结果:

let optionList = [
  {
    images: [
      {
        url: "test2"
      }
    ]
  },
  {
    images: [
      {
        url: "test4"
      }
    ]
  },
  {
    images: [
      {
        url: "test5"
      }
    ]
  }
];

以下是我当前的代码,它没有删除任何值:

 optionList.filter(ol => {
  let result = !ol.images.some(
    image => image.url === imagesToDelete.includes(image.url)
  );
  return result;
});

console.log(optionList);

标签: javascriptarraysobjectfilter

解决方案


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)


推荐阅读