将JSON值保存在Javascript / node js中提供的文件夹中



let obj={
print:{
"2343192u4":{
id:"01",
name:"linux file",
location:"System config"
},
"23438ufsdjh8":{
id:"02",
name:"windows file",
location:"System config"
}
},
hardware:{
"9058t05":{
no:"ct-01",
refrence:"down-tPO-01"
}
},
stack:{
"345t5fdfve":{
option1:"prefer first lost",
failure:"run backup"
}
},
backupdir:{
"cjksder8982w":{
files:"config file.json",
execute:"run after failure"
}
}
};

let Array=[{
filepath:"print"
},
{
filepath:"hardware"
},
{
filepath:"stack"
},
{
filepath:"backupdir"
},
];
Array.map((file)=>{
//console.log(file.filepath)
Object.keys(obj).forEach((key)=>{

if(key===file.filepath){
// fs.writeFile(path.join(__dirname,file.filepath,"system.json"), JSON.stringify(Object.values(obj)[0], null, 4))
console.log("yes");
}
})
});

我正在尝试从objJSON 对象中获取密钥并将其与数组文件路径进行比较,以便我可以在创建的 json 文件中推送值

在这里,通过使用fs,我正在尝试创建从数组中获得的文件夹

fs.writeFile(path.join(__dirname,file.filepath,"system.json"));

通过它,我在其中创建了文件夹和文件系统.json,我正在尝试比较来自obj json的键和来自数组的文件路径 并试图这样说

print/system.json

{
"2343192u4":{
id:"01",
name:"linux file",
location:"System config"
},
"23438ufsdjh8":{
id:"02",
name:"windows file",
location:"System config"
}
}

硬件/系统.json

{
"9058t05":{
no:"ct-01",
refrence:"down-tPO-01"
}
}

等等...

但问题是当我这样做时

JSON.stringify(Object.values(obj)[0], null, 4)

我在每个文件中都获得了相同的输出

print/system.json

{
"2343192u4":{
id:"01",
name:"linux file",
location:"System config"
},
"23438ufsdjh8":{
id:"02",
name:"windows file",
location:"System config"
}
}

硬件/系统.json

{
"2343192u4":{
id:"01",
name:"linux file",
location:"System config"
},
"23438ufsdjh8":{
id:"02",
name:"windows file",
location:"System config"
}
}

等等...

这里print hardware stack backupdir总是会更改,并且还有多个文件,因为这是系统随机生成的名称,这就是为什么我必须比较和来自对象的键并制作此名称的目录

我怎样才能将它们推送到具有相应值的不同文件夹中

尝试更改

fs.writeFileSync(path.join(__dirname,file.filepath,"system.json"),
JSON.stringify(Object.values(obj)[0], null, 4))

(仅查看obj中的第一个属性值)

fs.writeFileSync(path.join(__dirname,file.filepath,"system.json"),
JSON.stringify(obj[key], null, 4))

使用从正在处理的Array条目获得的key值在obj中查找属性对象。

Object.keys(obj).forEach((key)=>{中使用forEach可防止在找到匹配的文件路径时停止搜索。另一种选择是使用在找到文件名时中断的for of循环:

Array.forEach((file)=>{
for( let key of Object.keys(obj)) { 
if(key===file.filepath) {
fs.writeFileSync(path.join(__dirname,file.filepath,"system.json"),
JSON.stringify(obj[key], null, 4)); 
break;      
}
}
});

另外:避免使用全局构造函数的名称(如Array)作为变量名称 - 这是一个等待发生的错误:-)

最新更新