skip to Main Content

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


  1. will be very happy to help you.

    Instead of Object.keys(jsonData), you should use Object.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 with Object.keys

    Login or Signup to reply.
  2. 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] :

    if (jsonData.length > 0)
      console.log("JSON Fields---", Object.keys(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…

    let textData = '[ { "Active": "true", "Name": "User1", "primaryRegion": "US" }, { "Name": "user2", "primaryRegion": "US" }, { "Name": "user3", "primaryRegion": "US" }, { "Name": "user4", "primaryRegion": "US" }, { "Name": "user5", "primaryRegion": "US", "Currency": "USD" } ]';
    let jsonData = JSON.parse(textData);
    
    let keys = []
    jsonData.forEach(element => {
      Object.keys(element).forEach(key => {
        if (!keys.includes(key))
          keys.push(key);
      })
      
    });
    
    console.log("JSON Fields---", keys);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search