0

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");
 }
})
});

I am trying to fetch key from the obj JSON object and compare it with the Array filepath so I can push the value in created json file

here by using fs I am trying to create folder which I got from the array

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

by which I created folder and file system.json in it and I am trying to compare the key from the obj json and filepath from the array and trying to put like this

print/system.json

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

hardware/system.json

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

and so on ...

but the problem is when I do this

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

I am getting same output in every file

print/system.json

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

hardware/system.json

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

and so on ...

here print hardware stack backupdir always get changed and there are multiple more files as this is system random generated name thats why I have to compare and the key from object and make a directory of this name

how can I push them in different different folder with there respective value

  • Loop over the values instead of always referencing the first (`[0]`). In fact you can loop over the key-value pairs using `Object.entries` so you can use the directory based on the key and save the file inside based on the value. – CherryDT Feb 17 '22 at 11:39
  • How @CherryDT ? I didn't get it –  Feb 17 '22 at 11:55
  • `for (const [key, value] of Object.entries(obj)) await fs.writeFile(path.join(__dirname, key, 'system.json', JSON.stringify(value, null, 4)))` – CherryDT Feb 17 '22 at 15:46

1 Answers1

1

Try changing

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

(which only looks at the first property value in obj) to

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

which look up the property object in obj using the key value obtained from the Array entry being processed.

The use of forEach in Object.keys(obj).forEach((key)=>{ prevents stopping the search if a matching filepath is found. Another option would be to use a for of loop that breaks out if a file name has been found:

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;      
    }
  }
});

Also: avoid using the names of global constructors such as Array as variable names - it's a bug waiting to happen :-)

traktor
  • 17,588
  • 4
  • 32
  • 53
  • 1
    actually here I have provided name `array` in my code its having different name –  Feb 17 '22 at 13:49
  • and in place of `forEach` I should use `for..in` ? –  Feb 17 '22 at 13:53
  • 1
    A `for of` loop is usually recommended for Array entries because it [returns the values of numerically indexed items in the array](https://stackoverflow.com/q/29285897/5217142) – traktor Feb 17 '22 at 14:29
  • Careful, right now you create a _global variable_ `key` here because you are missing a declaration keyword! Also, suggestion: Use `Object.entries` instead of `Object.keys` so that you don't have `obj[key]` further down - you'd just do `for (const [key, value] of Object.entries(obj))` and then you'd have `JSON.stringify(value, null, 4)` below. Also, the `.map` doesn't seem to be very useful, you aren't mapping to anything... – CherryDT Feb 17 '22 at 15:44
  • @CherryDT thanks for the additional suggestions - I've edited to declare `key` before use and replaced `map` with `forEach` in the outer loop. I recommend always running JavaScript in strict node if for no other reason than the compiler generates an error if you fail to declare variables when executing the code. I agree the code could benefit from further improvements but personally would probably have iterated over entries of `obj` in the outer loop if rewriting the code entirely. – traktor Feb 17 '22 at 21:41