Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read or select value names from .json file to push in the array

if myjson.js file data:

{
  "key1": [
    {
      "name1": [
        "word1",
        "word2",
      ],
      "name2": [
        "word3",
        "word4",
      ]
    }
  ]
}

loaded:

  var jsonData = fs.readFileSync("myjson.json", "utf8");
  const data = JSON.parse(jsonData);

  console.log(Object.keys(data));

output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[ 'key1' ]

or:

 console.log(Object.values(data));

output:

[
  [
    {
      name1: [Array],  
      name2: [Array],  
    }
  ]
]

How properly read or select only value names (without ‘value’ values – arrays) to create array of value names:

[
   "name1",  
   "name2",  
]

>Solution :

You can use Array#flatMap over each of the arrays of objects.

const data={key1:[{name1:["word1","word2",],name2:["word3","word4",]}]};
let res = Object.values(data).flatMap(x => x.flatMap(Object.keys));
console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading