How to find keys from undefined schema

Viewed 16

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.

2 Answers

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)

Try this one

let header = new Set();
array.forEach((a) => {
  Object.keys(a).forEach((item) => {
    header.add(item);
  });
});
console.log(header);

Related