{
"ID": "5c9b2de495e8d81ef437539e",
"WeightingFactor": "BIC",
"TargetAmount": 1000,
"FilterCondition": {
"_cls": "ComplexFilter",
"Condition": "AND",
"Rules": [{
"_cls": "Filter",
"Field": "MOODYSFOREIGNCURRENCYCEILINGRATING",
"Operator": "in list",
"Value": "A1,A2,A3"
},
{
"_cls": "Filter",
"Field": "ASOFDATE",
"Operator": "less or equal",
"Value": "26 Nov 2028"
},
{
"_cls": "ComplexFilter",
"Condition": "OR",
"Rules": [{
"_cls": "Filter",
"Field": "ASOFDATE",
"Operator": "less or equal",
"Value": "26 Nov 2028"
},
{
"_cls": "Filter",
"Field": "ASOFDATE",
"Operator": "less or equal",
"Value": "26 Nov 2029"
}
]
}
],
"Not": false
}
}
需要将所有地方的“field”
重命名为category
。请建议如何使用任何可用的方法?
尝试了字符串化
和替换
。但它不起作用
预期输出:
{
"ID": "5c9b2de495e8d81ef437539e",
"WeightingFactor": "BIC",
"TargetAmount": 1000,
"FilterCondition": {
"_cls": "ComplexFilter",
"Condition": "AND",
"Rules": [{
"_cls": "Filter",
"Category": "MOODYSFOREIGNCURRENCYCEILINGRATING",
"Operator": "in list",
"Value": "A1,A2,A3"
},
{
"_cls": "Filter",
"Category": "ASOFDATE",
"Operator": "less or equal",
"Value": "26 Nov 2028"
},
{
"_cls": "ComplexFilter",
"Condition": "OR",
"Rules": [{
"_cls": "Filter",
"Category": "ASOFDATE",
"Operator": "less or equal",
"Value": "26 Nov 2028"
},
{
"_cls": "Filter",
"Category": "ASOFDATE",
"Operator": "less or equal",
"Value": "26 Nov 2029"
}
]
}
],
"Not": false
}
}
最佳答案
您可以将给定 JSON 中的字符串 "field":
替换为 "category":
字符串。
var json = JSON.stringify({ field: { field: 'foo' } }),
newJSON = json.replace(/"field":/g, '"category":');
console.log(JSON.parse(newJSON));
经典的替代品
function replace(object, source, target) {
return Object.assign(...Object.entries(object).map(([k, v]) => ({
[k === source ? target : k]: v && typeof v === 'object'
? replace(v, source, target)
: v
})));
}
var object = { field: { field: 'foo' } },
newObject = replace(object, 'field', 'category');
console.log(newObject);
关于javascript - 如何在各级重命名 JSON 嵌套对象中的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55417490/