首页 > 解决方案 > 按属性值从深度嵌套的对象数组中删除对象

问题描述

考虑我有一个嵌套对象数组。一种可能的示例场景可能是:

content: [
    {
        prop1: someValue,
        prop2: someValue,
        content: [
            {
                prop2: someValue,
                prop3: someValue,
                myProperty: myValue
            },
            {
                prop1: someValue,
                prop3: someValue,
                myProperty: otherValue
            }
        ]
    },
    {
        prop5: someValue,
        prop2: someValue
    }
]

以下是可能性:

我的要求:

到目前为止我的尝试:

  private removeObjects(content: any, values: string[]): any {
    if (!content || content.length === 0) {
      return
    }
    content = content.filter((c) => {
      if (!c.myProperty) return true
      return c.myProperty.indexOf(values) > 0
    })
    // Here is my problem since I am supposed to do a recursive call on each of child contents,
    // how do I merge back the original array?
    return this.removeObjects(content, values)
  }

标签: javascriptarraystypescriptobjectfilter

解决方案


以下递归返回一个新数组而不改变原始数组

const content = [{
    prop1: "someValue",
    prop2: "someValue",
    content: [{
        prop2: "someValue",
        prop3: "someValue",
        myProperty: "myValue"
      },
      {
        prop1: "someValue",
        prop3: "someValue",
        myProperty: "otherValue"
      }
    ]
  },
  {
    prop5: "someValue",
    prop2: "someValue"
  }
]

function removeObjects(content) {
  return content.reduce((arr, obj) => {
    if (obj["myProperty"] && obj["myProperty"] === "myValue") {
      return arr
    } else if (obj["content"] && obj["content"].length) {
      arr.push({ ...obj,
        content: removeObjects(obj["content"])
      })
      return arr
    } else {
      arr.push(obj);
      return arr;
    }
  }, []);
}



console.log(removeObjects(content))

预期输出:

const content = [{
        prop1: "someValue",
        prop2: "someValue",
        content: [
          {
            prop1: "someValue",
            prop3: "someValue",
            myProperty: "otherValue"
          }
        ]
      },
      {
        prop5: "someValue",
        prop2: "someValue"
      }
    ]

推荐阅读