根据另一个数组中的值删除嵌套对象数组中的值

时间:2019-07-18 18:17:59

标签: javascript arrays object filter

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

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);

3 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:1)

有两个问题。通常,您从未真正在迭代中修改images数组,而是根据optionList进行过滤,而optionList并未真正删除任何项(因为如果您没有图像,则声明为空数组)。

您需要迭代optionList,并根据该列表修改images数组以删除。

您可以将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);

答案 2 :(得分:-1)

filter()返回一个新数组,并且不对原始数组进行突变

尝试做

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>