-4

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.

jabaa
  • 5,844
  • 3
  • 9
  • 30

2 Answers2

2

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)
Rajesh
  • 24,354
  • 5
  • 48
  • 79
1

Try this one

let header = new Set();
array.forEach((a) => {
  Object.keys(a).forEach((item) => {
    header.add(item);
  });
});
console.log(header);
hgb123
  • 13,869
  • 3
  • 20
  • 38
jobayer
  • 156
  • 1
  • 5