簡體   English   中英

如何通過ID刪除子對象並使用過濾器檢索父對象

[英]How to remove child by id and retrive the parent objects using filter

我正在嘗試通過不匹配刪除子ID來過濾父對象。 如果沒有子代,則應刪除父代。

我這樣嘗試,但不起作用。

var rm = 7;

var objects = [
  {
    name: "parent1",
    id: 1,
    blog: [
      {
        name: "child1",
        id: 1
      },
      {
        name: "child2",
        id: 2
      }
    ]
  },
  {
    name: "parent2",
    id: 2,
    blog: [
      {
        name: "child3",
        id: 3
      },
      {
        name: "child4",
        id: 4
      }
    ]
  },
  {
    name: "parent3",
    id: 3,
    blog: [
      {
        name: "child5",
        id: 5
      },
      {
        name: "child6",
        id: 6
      }
    ]
  },
  {
    name: "parent4",
    id: 3,
    blog: [
      {
        name: "child6",
        id: 7
      }

    ]
  },
]


var result = objects.filter(value => {
    if(!value.blog) return;
  return value.blog.some(blog => blog.id !== rm)
})

console.log(result);

這有什么問題,或者有人向我展示了正確的方法?

尋找 :

  1. 如果ID與rm相同,則需要刪除博客,父級必須與其他子級存在。

  2. 如果沒有子代,則需要刪除父代,再刪除子代。

現場演示

循環瀏覽父母名單,然后在該循​​環中,嘗試首先刪除具有給定ID的博客。 完成此操作后,您可以檢查blogs屬性是否為空,如果是,則將其過濾掉:

// We're going to filter out objects with no blogs
var result = objects.filter(value => {
  // First filter blogs that match the given id
  value.blog = value.blog.filter(blog => blog.id !== rm);
  // Then, if the new length is different than 0, keep the parent
  return value.blog.length;
})

我認為以下代碼是您正在尋找的

var result = objects.map(value => {
   const blog = value.blog.filter(blog => blog.id !== rm);
   if(blog.length === 0) {
        return;
   }
   value.blog = blog;
   return value;
}).filter(item => item);

演示: https : //jsfiddle.net/7Lp82z4k/3/

var result = objects.map(parent => {
parent.blog = parent.blog.filter(child => child.id !== rm);
return parent}).filter(parent => parent.blog && parent.blog.length > 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM