skip to Main Content

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:

[ '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",  
]

2

Answers


  1. 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);
    Login or Signup to reply.
  2. Note key1 is actually an array.

    const obj = {
      "key1": [
        {
          "name1": [
            "word1",
            "word2",
          ],
          "name2": [
            "word3",
            "word4",
          ]
        }
      ]
    };
    
    console.log(Object.keys(obj.key1[0]));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search