-1

I have the below JSON response:

{
  "A":{"Option1":true,"Option2":true,"Option3":false}
  "B":{"OptionX":true,"OptionY":true,"OptionZ":false}
 }

I want to get the following values in a string: Option1, Option2, OptionX, OptionY

I have tried the below but with no luck:

  Array.from(this.model).forEach(child => {
    console.log(child, 'child name')
  });
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Vida
  • 89
  • 1
  • 8

3 Answers3

1

Use flatMap() with filter() where you map over each key using Object.keys()

const data = {
  "A": {"Option1":true,"Option2":true,"Option3":false},
  "B": {"OptionX":true,"OptionY":true,"OptionZ":false}
};
 
const res = Object.values(data).flatMap(o => Object.keys(o).filter(k => o[k]));

console.log(res)
0stone0
  • 34,288
  • 4
  • 39
  • 64
0
for (const record of Object.values(json)) {
  for (const [key, value] of Object.entries(record)) {
    if (value) {
      console.log(key);
    }
  }
}

// or

const keys = Object
  .values(json)
  .map(record => Object
    .entries(record)
    .filter(([key, value]) => value)
    .map(([key]) => key)
  )

-1

const obj = {
  "A": {
    "Option1": true,
    "Option2": true,
    "Option3": false
  },
  "B": {
    "OptionX": true,
    "OptionY": true,
    "OptionZ": false
  }
}

const result = Object.values(obj).flatMap(o => Object.entries(o).filter(([key, value]) => value).map(([key]) => key))

console.log(result)
Konrad
  • 21,590
  • 4
  • 28
  • 64