0

I have a JSON file that I want to extract a field from.

{
"player": [
    {
        "Position": "TEST",
        "Name": "TEST",
        "Squad_No": "TEST",
        "Club": "TEST",
        "Age": "TEST"
    },
    {
        "Position": "",
        "Name": "",
        "Squad_No": "",
        "Club": "",
        "Age": ""
    },
    ]
    }

I would like to take the "Name:" field and put it into a file with this format:

[["TEST",0,0,"","TEST"],["ns1.0a",1,0,"","ns1.0a"],
["ns1.1b",2,0,"","ns1.1b"],["ns1.2",3,0,"","ns1.2"]]

The aim is to load this file into a table using the Redips load functionality.

Any ideas on the best method to accomplish this? Any help would be greatly appreciated.

codtetsam
  • 15
  • 5

2 Answers2

1

Use map

arr = arr.player.map( (s,i) => ( [ s.Name , i, 0, "" , s.Name ] ) );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • This worked, thanks. Along with @Bougarfaoui El houcine answer below. Just needed to use JSON.stringfy when writing to file. Thanks for the help, much appreciated. – codtetsam Nov 29 '17 at 15:11
0

After reading the file you can do as @gurvinder372 said :

var fs = require('fs');
var obj;
fs.readFile('file', 'utf8', (err, data) => {
  if (err) throw err;
  data = JSON.parse(data);
  data = data.player.map( (s,i) => ( [ s.Name , i, 0, "" , s.Name ] ) );
  console.log(data);
});
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37