【发布时间】:2019-10-04 18:01:35
【问题描述】:
这似乎是一项很容易的任务,但由于某种原因被卡住了!我尝试了我在SE中找到的几种解决方案,主要是递归迭代数组/对象,例如 How to iterate over an array and remove elements in JavaScript 和 Looping through array and removing items, without breaking for loop(以及许多其他人)但没有运气!
我有这个数组
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test0"
},
{
"id": "sessionIgnore",
"type": "string",
"input": "text",
"operator": "equal",
"value": "ignore0"
},
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test1"
},
{
"id": "sessionIgnore",
"type": "string",
"input": "text",
"operator": "equal",
"value": "ignore1"
},
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test2"
},
{
"id": "sessionIgnore",
"type": "string",
"input": "text",
"operator": "equal",
"value": "ignore2"
}
]
}
]
},
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test3"
},
{
"id": "sessionIgnore",
"type": "string",
"input": "text",
"operator": "equal",
"value": "ignore3"
}
]
}
],
"valid": true
}
我想删除所有 sessionIgnore 元素
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test0"
},
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test1"
},
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test2"
}
]
}
]
},
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test3"
}
]
}
],
"valid": true
}
在我的情况下似乎是什么问题: 在这两种情况下,我都会递归地遍历数组
-
delete x/array.slice()方法: 似乎保留了对空数组元素的引用,然后我必须调用清理方法,我希望避免这种情况 - 我创建了一个 arrayRemove() 函数,用于从给定数组中删除 x 元素,但在这种情况下,我似乎有一个逻辑问题,并且在数组的第二级之后我无法解析任何内容
感谢任何帮助!
编辑: 如果规则对象中只有一个 sessionIgnore 元素,我希望删除整个部分 即引用上述数组,如果值为 ignore2 的 sessionIgnore 是其“规则”组中的唯一对象,我希望删除整个部分 编辑2: 添加了预期的结果
编辑关于 nina 的对话:
如果对象是这样的:
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test1"
},
{
"id": "sessionIgnore",
"type": "string",
"input": "text",
"operator": "equal",
"value": "ignore1"
},
{
"condition": "AND",
"rules": [
{
"id": "sessionIgnore",
"type": "string",
"input": "text",
"operator": "equal",
"value": "ignore2"
}
]
}
]
}
我想要这个
{
"condition": "AND",
"rules": [
{
"id": "loc1",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test1"
}
]
}
【问题讨论】:
-
这不是一个数组 - 这是一个对象。
-
您想要相同的对象,还是需要更改数据的新对象?
-
@VLAZ 但是属性
"rules"是一个数组。我猜 OP 指的是这个属性,而不是整个对象。 -
@PedroCorso 是的!正是
-
@NinaScholz 我不介意,只要我有一个没有 sessionIgnore 值的数组:D
标签: javascript arrays