javascriptarraysextractfield

Extract field names from an object of array in Javascript


I would like to extract field names from an object of array, called results, in Javascript that has the following structure

    Object { data: (5) […] }
    ​
     data: Array(5) [ {…}, {…}, {…}, … ]
    ​​
      0: Object { nClients: 4 }
    ​​
      1: Object { name: "test1", roll_no: 321, branch: "it" }
    ​​
      2: Object { name: "test2", roll_no: 321, branch: "it" }
    ​​
      3: Object { name: "test3", roll_no: 321, branch: "it" }
    ​​
      4: Object { name: "test4", roll_no: 321, branch: "it", … }
    
      length: 5
    ​​
     <prototype>: Array []

​
<prototype>: Object { … }

I would like to extract a list of fields like [nClients, name, roll_no, branch]. Any suggestion? Thank you!


Solution

  • I would suggest you merge all your objects together within your array using Object.assign(...arr), and then grab the keys of that object with Object.keys():

    const arr = [ { nClients: 4 }, { name: "test1", roll_no: 321, branch: "it" }, { name: "test2", roll_no: 321, branch: "it" }, { name: "test3", roll_no: 321, branch: "it" }, { name: "test4", roll_no: 321, branch: "it" } ];
    const res = Object.keys(Object.assign(...arr));
    console.log(res);