How to convert an array of file names to JSON and add a key

90
June 08, 2019, at 03:40 AM

I'm setting up a new web page that shows all of the files in a folder. How can I convert an array of document names to JSON?

To do this, I know I need a JSON object to send from the server to the front end. I currently have an array of the document names but I don't know how to convert this to JSON and add a key to each of the values. I've tried using JSON.stringify() and numerous other ways given by users here, to no avail.

let docs = [];
    fs.readdir(../../docs', function(err, docs) {
        let json = JSON.stringify(docs);
        res.send(json);

I expect the output to be

[
   {
      "catalogName": "doc.pdf"
   },
   {
      "catalogName": "doc2.pdf"
   }
]

I am currently getting ["doc.pdf", "doc2.pdf"]

Answer 1
let json = JSON.stringify(docs.map((doc) => { 
  return {
    catalogueName: doc
  };
}))
Answer 2

You could map the value as object.

var array = ["doc.pdf", "doc2.pdf"], 
    result = array.map(catalogName => ({ catalogName })); 
 
console.log(result);

Answer 3

Try this ,

fs.readdir('.', function(err, docs) {
   const docMap = docs.reduce((docMap,doc)=>{
        return docMap.concat({"catalogName":doc})
    },[])
    console.log(docMap)
});

It generates output like

[ { catalogName: 'node_modules' },
  { catalogName: 'package.json' },
  { catalogName: 'README.md' },
  { catalogName: 'test.js' } ]

Play with this code, you might need to change the directory! Have fun.

Rent Charter Buses Company
READ ALSO
ID From Database Not Usable In API

ID From Database Not Usable In API

I created an API using Loopback, and connected it to a MongoDBI loaded some data into my database via a JSON file, and I can access that data without issue

122
Attribute based access control implementation with nodejs [on hold]

Attribute based access control implementation with nodejs [on hold]

Is it possible to implement attribute-based access control with nodejs without using any external library or npm module? If you know any implemented sample please share it with me

119
Node.js web service using Puppeteer to create PDF creates empty PDF file

Node.js web service using Puppeteer to create PDF creates empty PDF file

The following code is from a Nodejs REST service

127
How do I associate a websocket with a user with express-session and passport?

How do I associate a websocket with a user with express-session and passport?

My goal here is to send messages to sockets belonging to users, so users see their info only or for their user roles

141