javascript - 按属性值从深度嵌套的对象数组中删除对象
问题描述
考虑我有一个嵌套对象数组。一种可能的示例场景可能是:
content: [
{
prop1: someValue,
prop2: someValue,
content: [
{
prop2: someValue,
prop3: someValue,
myProperty: myValue
},
{
prop1: someValue,
prop3: someValue,
myProperty: otherValue
}
]
},
{
prop5: someValue,
prop2: someValue
}
]
以下是可能性:
- 结构开始于,
content[]
但后代可能有也可能没有content
财产。 - 层次结构的级别可以是任意数量。
- 对象包含的属性并不总是相同的,即一个对象可能具有 x、y、z 属性,而另一个对象可能具有 v、w、z 属性。
- 如果层次结构中的任何对象有
myProperty
键,则不会有content
键。 - 层次结构中的多个对象可以具有
myProperty
value'myValue
。
我的要求:
- 如果在任何级别,对象具有具有
myProperty
值的属性,myValue
则从层次结构中删除整个对象(不仅仅是属性)。
到目前为止我的尝试:
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)
}
解决方案
以下递归返回一个新数组而不改变原始数组
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"
}
]
推荐阅读
- jupyter-notebook - 学生在 nbgrader 中提交作业后更新测试以对其评分
- php - 付款确认php+android
- android - 有没有办法批准用户将数据插入到android中的firebase数据库中?
- sql-server - 无法访问 SQL Server 数据库镜像服务器
- node.js - 多阶段 Dockerfile 导致空间不足
- ios - `Protocol 的问题只能用作通用约束,因为它具有 Self 或关联的类型要求`
- r - 将间隔文本数据转换为数据框
- reactjs - 将 Snipcart 添加到 Gatsby
- sql-server - 如何从 SQL Server 中的日期时间列中删除尾随零
- ssl - 是否可以使用公认的 SSL 证书运行 IIS Express 实例?