【发布时间】:2020-12-23 23:21:12
【问题描述】:
这篇文章可能看起来很长,但很容易理解,如果不是,我会添加更多细节
我有 criteria 数组,看起来像:
let criteria = [
"and",
{
"Collection": "persons",
"Property": "phone",
"operator": "eq",
"operatorValue": "$p:phone"
},
{
"Collection": "persondetails",
"Property": "country",
"operator": "eq",
"operatorValue": "$p:country"
},
["or",
{
"Collection": "persons",
"Property": "city",
"operator": "eq",
"operatorValue": "$p:city"
}]
]
criteria的特征:
- 它可以有嵌套数组。
- 第一项数组(或嵌套数组)总是“与”或“或”
- 数组中的第二个项目,项目可以是具有此特定结构的对象
{ "Collection": "persons", "Property": "phone", "operator": "eq", "operatorValue": "$p:phone" }
或者它可以是一个数组,例如:
["or", { "Collection": "persons", "Property": "city", "operator": "eq", "operatorValue": "$p:city" }]
- 对象永远不会是嵌套对象
还有一个parameters对象:
let parameters = {phone:"23138213", "country": "Russia", "city":"york"}
目的是递归遍历criteria 数组中的所有operatorValue 属性,如果遇到诸如$p:phone 之类的值,则将其替换为parameters["phone"] 求值的任何值。
预期输出:
[
"and",
{
"Collection": "persons",
"Property": "phone",
"operator": "eq",
"operatorValue": "23138213"
},
{
"Collection": "persondetails",
"Property": "country",
"operator": "eq",
"operatorValue": "Russia"
},
["or",
{
"Collection": "persons",
"Property": "city",
"operator": "eq",
"operatorValue": "york"
}]
]
我能够递归遍历数组。唯一的问题是我不知道如何修改原来的criteria变量。
请参阅 repl 中的第 43 行。 item[1]=parameters[item[1].split('$p:')[1]]
我理解为什么它不会修改标准,因为这里的 item 是完全不同范围内的不同变量。
尝试失败:
function traverse(obj,parameters){
obj.forEach((item,index)=>{
if( typeof item == 'string' ){
//do nothing
}
else if( !(item instanceof Array)){
Object.entries(item).forEach((item,index)=>{
if( item[1] instanceof Array){
traverse(item,parameters);
}else{
if(item[1].startsWith('$p:')){
item[1]=parameters[item[1].split('$p:')[1]] //values dont get replaced for obvious reason
console.log(item[1])
}
}
})
}
else if( item instanceof Array){
traverse(item,parameters);
}
})
}
traverse(criteria,parameters)
console.log(criteria)
我该如何解决这个问题?
【问题讨论】:
标签: javascript node.js algorithm recursion data-structures