Search code examples
javascriptarraysgroup

How to find keys from undefined schema


Suppose I have following array

array = [
 {
  optionA: "QA1",
  optionB: "QB1",
  optionC: "QC1",
  optionD: "QD1",
 },
 {
  optionA: "QA2",
  optionB: "QB2",
  optionC: "QC2",
  optionD: "QD2",
  optionE: "QD2",
 },
 {
  optionA: "QA3",
  optionB: "QB3",
 }
] 

Expected output

tableHeader = {OptionA,OptionB,OptionC,OptionD,OptionE}

Wanted display questions data in a table format, which is not organised and has n number for options.


Solution

  • You can get all keys as follows

    const array = [{optionA: "QA1",optionB: "QB1",optionC: "QC1",optionD: "QD1",},{optionA: "QA2",optionB: "QB2",optionC: "QC2",optionD: "QD2",optionE: "QD2",},{optionA: "QA3",optionB: "QB3",}]
    
    const allKeys = Object.keys(Object.assign({}, ...array))
    console.log(allKeys)