2

I have this array of objects and I want to show all value in each object:

var array = [{obj1:{property1:"value1",property2:"value2",property3:"value3"}},
          {obj2:{property1:"value1",property2:"value2",property3:"value3"}},
          {obj3:{property1:"value1",property2:"value2",property3:"value3"}}];

When I try something like this I only get to show the key but not the value

for (let i in array){
    for (let key1 in array[i]) {

Any help?

Lothar
  • 39
  • 5
  • You can use: `array[i][key1]`, E.g. `for (let i in array){ for (let key1 in array[i]) { console.log('value is ' + array[i][key1]); } }`. – acdcjunior May 08 '20 at 17:34

1 Answers1

0

The Object.values() returns an array of values of the Object passed to it.

You can then use flatMap twice to flatten the nested object array and fetch all the values.

var array = [{
    obj1: {
      property1: "value1",
      property2: "value2",
      property3: "value3"
    }
  },
  {
    obj2: {
      property1: "value1",
      property2: "value2",
      property3: "value3"
    }
  },
  {
    obj3: {
      property1: "value1",
      property2: "value2",
      property3: "value3"
    }
  }
];

function getAllValues(array) {
  return array.flatMap(o => Object.values(o))
              .flatMap(o => Object.values(o))
}
console.log(getAllValues(array));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44