I have an json data like this
[
{
"Name": "User1",
"primaryRegion": "US"
},
{
"Name": "user2",
"primaryRegion": "US"
},
{
"Name": "user3",
"primaryRegion": "US"
},
{
"Name": "user4",
"primaryRegion": "US"
},
{
"Name": "user5",
"primaryRegion": "US"
}
]
I just want to get the unique value of keys (Json Headers) in an array like this:
["Name", "primaryRegion"]
I tried below code but not getting expected result:
let jsonData = JSON.parse(fs.readFileSync('./test/sampleData1.json', 'utf8'));
console.log("JSON Fields---", Object.keys(jsonData));
It gives below output:
JSON Fields--- [
'0', '1', '2',
'3', '4'
]
2
Answers
will be very happy to help you.
Instead of
Object.keys(jsonData)
, you should useObject.keys(jsonData.reduce((obj, field) => ({...obj, ...field}), {}))
Since your json file is an array and
Object.keys
return the keys of the object (in JavaScript array is an object too and its keys are indexes (0, 1, 2 , …) thats why you have in your array numbers['0', '1', '2', '3', '4' ]
In my example, I’m accumulating the array of objects into single object (with
reduce
), and receiving keys from it withObject.keys
The json data is an array of objects, so if you have at least one object in the array, and if all properties are the same on each object item, you can simply get the keys of the first at jsonData[0] :
But if you have different keys on some of the objects, and you want to find out each of them, you have to iterate the array of objects, and add the key to a separate array [keys] when it is not included on that [keys] array…