我试着从这一点出发:
{
"Level":"A",
"Group LVL2":{
"Level":"B",
"Group LVL3":{
"Level":"C"
}}}对此
{
"Level":"C",
"Group LVL2":{
"Level":"C",
"Group LVL3":{
"Level":"C"
}}}因此,我基本上希望将json键的所有值替换为相同的值。这是代码im的部件,使用:
const fs = require('fs');
const fileName = './' + (Profile) + ".json";
const file = require(fileName);
const key = (Root);
file[Root] = (Value);
fs.writeFile(fileName, JSON.stringify(file, null, 2), function writeJSON(error) {
if (error) return console.log(error);但它只替换了第一个json组/行的级别值:
{
"Level":"THIS WILL BE REPLACED",
"Group LVL2":{
"Level":"THIS WILL NOT BE REPLACED",
"Group LVL3":{
"Level":"THIS WILL NOT BE REPLACED"
}
}
}希望我能找到解决这个问题的办法,我相信你!(网上似乎没有任何初学者友好的解决方案)
发布于 2021-11-12 16:18:58
下面是这类问题的一般解决方案,也许你可以根据你的问题来提高效率。它循环遍历嵌套对象本身的对象的所有键,对json中的每个对象进行递归,并更新"Level“键。
function replaceValues(obj) {
if(obj.hasOwnProperty(key))
obj[key] = value;
for (let property of Object.keys(obj)) {
if (typeof(obj[property]) === "object") {
replaceValues(obj[property]);
}
}
}在您提供的Value = "D"数据上进行测试
{
"Level": "D",
"Group LVL2": {
"Level": "D",
"Group LVL3": {
"Level": "D"
}
}
}https://stackoverflow.com/questions/69945474
复制相似问题