how can I access to one of the values of one of the objects in an Array in JavaScript?

Viewed 31

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?

1 Answers

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));

Related