0

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",  
]
emss
  • 65
  • 9
  • 2
    Using `Object.keys` is correct, but you need to select the correct object to get the keys from – Matthew Herbst Dec 22 '22 at 02:30
  • 1
    Does this answer your question? [Finding all the keys in the array of objects](https://stackoverflow.com/questions/66452572/finding-all-the-keys-in-the-array-of-objects) – pilchard Dec 22 '22 at 02:32

2 Answers2

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);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

Note key1 is actually an array.

const obj = {
  "key1": [
    {
      "name1": [
        "word1",
        "word2",
      ],
      "name2": [
        "word3",
        "word4",
      ]
    }
  ]
};

console.log(Object.keys(obj.key1[0]));
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91