如何解决遍历数组并在JavaScript中修改对象属性的值
该帖子似乎冗长,但很容易理解,否则,我将添加更多详细信息
我有一个criteria
数组,它看起来像:
let criteria = [
"and",{
"Collection": "persons","Property": "phone","operator": "eq","operatorValue": "$p:phone"
},{
"Collection": "persondetails","Property": "country","operatorValue": "$p:country"
},["or","Property": "city","operatorValue": "$p:city"
}]
]
criteria
的特征:
- 它可能具有嵌套数组。
- 第一项数组(或嵌套数组)始终为“和”或“或”
- 数组中的第二个项目以后,该项目可以是具有此特定结构的对象
{ "Collection": "persons","operatorValue": "$p:phone" }
或者它可以是像这样的数组:
["or",{ "Collection": "persons","operatorValue": "$p:city" }]
- 对象永远不会是嵌套对象
还有一个parameters
对象:
let parameters = {phone:"23138213","country": "Russia","city":"york"}
目标是递归遍历operatorValue
数组中的所有criteria
属性,如果遇到诸如$p:phone
之类的值,则将其替换为{{1} }评估。
预期输出:
parameters["phone"]
我能够递归地遍历数组。唯一的问题是我不知道如何修改原始的[
"and",{
"Collection": "persons","operatorValue": "23138213"
},{
"Collection": "persondetails","operatorValue": "Russia"
},"operatorValue": "york"
}]
]
变量。
请分别参见第43行。 criteria
我知道为什么它不会修改条件,因为这里的项目在不同范围内是一个完全不同的变量。
尝试失败:
item[1]=parameters[item[1].split('$p:')[1]]
我该如何解决这个问题?
解决方法
您可以简化功能。您无需遍历对象的条目。您也不需要split
operationValue
。 parameters
键中存在该映射键Property
。
- 遍历数组中的每个项目,并检查该项目是否为
Array
。 - 如果是,请递归调用该项目上的
traverse
。 - 如果它是一个对象,则用
operatorValue
更新其parameters[val.Property]
属性
function traverse(arr,parameters) {
for (const item of arr) {
if (Array.isArray(item))
traverse(item,parameters)
else if (typeof item === 'object')
item.operatorValue = parameters[item.Property]
}
return arr
}
let criteria=["and",{Collection:"persons",Property:"phone",operator:"eq",operatorValue:"$p:phone"},{Collection:"persondetails",Property:"country",operatorValue:"$p:country"},["or",Property:"city",operatorValue:"$p:city"}]],parameters = {phone:"23138213","country": "Russia","city":"york"};
console.log(traverse(criteria,parameters))
,
您需要使用对象的键来分配值。
function traverse(obj,parameters) {
obj.forEach(item => {
if (item instanceof Array) return traverse(item,parameters);
if (item?.operatorValue?.startsWith('$p:')) {
item.operatorValue = parameters[item.operatorValue.split('$p:')[1]];
}
});
}
const
criteria = ["and",{ Collection: "persons",Property: "phone",operator: "eq",operatorValue: "$p:phone" },{ Collection: "persondetails",Property: "country",operatorValue: "$p:country" },Property: "city",operatorValue: "$p:city" }]],parameters = { phone: "23138213","city": "york" };
traverse(criteria,parameters);
console.log(criteria);
.as-console-wrapper { max-height: 100% !important; top: 0; }
,
干净的递归版本:
const traverse = ([conj,...nodes],params) => [
conj,... nodes .map (node => Array .isArray (node)
? traverse (node,params)
: {... node,operatorValue: params [nodes .Property]}
)
]
const criteria = ["and",{Collection: "persons",operatorValue: "$p:phone"},{Collection: "persondetails",operatorValue: "$p:country"},operatorValue: "$p:city"}]]
const parameters = {phone:"23138213","city":"york"}
console .log (traverse (criteria,parameters))
.as-console-wrapper {min-height: 100% !important; top: 0}
仅当adiga的简化形式证明对象的Property
节点的值与operatorValue
的后缀相同时,此方法才有效。如果没有,我可能会使用正则表达式替换来处理它,并将其分离为一个辅助函数:
const replaceOpValue = (params) => (obj) => ({
... obj,operatorValue: obj .operatorValue .replace (/\$p:(.+)/,((_,key) => params [key]))
})
const traverse = ([conj,params)
: replaceOpValue (params) (node)
)
]
,
这是一个使用 object-scan 的解决方案。根据您的要求,可能会更加灵活和可维护
// const objectScan = require('object-scan');
const criteria = [ 'and',{ Collection: 'persons',Property: 'phone',operator: 'eq',operatorValue: '$p:phone' },{ Collection: 'persondetails',Property: 'country',operatorValue: '$p:country' },[ 'or',Property: 'city',operatorValue: '$p:city' } ] ];
const substitute = (obj,params) => objectScan(['**.operatorValue'],{
rtn: 'count',filterFn: ({ value,parent,property }) => {
if (value.startsWith('$p:') && value.slice(3) in params) {
parent[property] = params[value.slice(3)];
return true;
}
return false;
}
})(obj);
console.log(substitute(criteria,{ phone: '23138213',country: 'Russia',city: 'york' })); // returns number of substitutions
// => 3
console.log(criteria);
// => [ 'and',operatorValue: '23138213' },operatorValue: 'Russia' },operatorValue: 'york' } ] ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>
免责声明:我是object-scan
的作者版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。