简体   繁体   中英

How to make complex Json fit a Javascript object

The backend of my webapp, written in node.js interacts with Json file, with a specific format that I thought not so complex but apparently is.

The structure of my json file is as such :

{
    "data": [
      {
        "somefield": "ioremipsum",
        "somedate" : "2018-08-23T11:48:00Z",
        "someotherdate" : "2018-08-23T13:43:00Z",
        "somethingelse":"ioremipsum",
        "files": [
          {
            "specificfieldinarray": "ioremipsum",
            "specificotherfieldinarray": "ioremipsum"
          },
          {
            "specificfieldinarray": "ioremipsum",
            "specificotherfieldinarray": "ioremipsum"
          },
          {
            "specificfieldinarray": "ioremipsum",
            "specificotherfieldinarray": "ioremipsum"
          }
        ]
      }
    ]
  }

I try to make this answer fit a JS object like this :


const file =  require('specificJsonFile.json');

let fileList = file;

And I need to loop through my 'files' array, for further treatments, but unfortunately, my JS object looks like this :


{ data:
   [ { somefield: "ioremipsum",
       somedate : "2018-08-23T11:48:00Z",
       someotherdate : "2018-08-23T13:43:00Z",
       somethingelse:"ioremipsum",
       files: [Array] } ] }

Please forgive me if this is obvious, for I am still a beginner with JS.

That's only how console.log logs deep objects. To get a deeper output, you can use util.inspect

const util = require('util');
console.log(util.inspect(yourObject, {showHidden: false, depth: null}));

To loop each data's files, simply loop data, then its files

yourObject.data.forEach(d => {
    d.files.forEach(file => console.log(file));
});

It looks like there is nothing wrong there and the console is abbreviating the log.

Try accessing the files list with the following code:

const filesList = file.data[0].files

and then

console.log(filesList) to check that it's eventually working.

Hope it helps!

let fileList = file.data[0].files;

This will create an array of only your files array.

You can console.log(fileList)

Or whatever you like with the data.

Based on your comment, try the of keyword instead of in keyword to get the behaviour you expected.

for (let file of fileList){
    console.log(file);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

You can use for in

for (item in fileList.data) {
    for (file in fileList.data[item].files) {
         let data = fileList.data[item].files[file];

         // process the data         

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM