0

I have following object -:

const response = { 'ALICE': { CLUSTER:'3', ... } }

How i can access property CLUSTER ?. The response object is coming from server and the outer key i.e 'ALICE' here is unknown, it can be any possible name, but value i.e {CLUSTER: '3', ...} has fixed properties.

Aman Gupta
  • 23
  • 1
  • 3

2 Answers2

0

Just map over the keys in your object, e.g.

Object.keys(response).map((key: string) => {
  const alice = response[key];
  alice["CLUSTER"]...
});

If you use typescript, you could define it even better, as a map from string as key and your final type as inner object.

Martin Seeler
  • 6,874
  • 3
  • 33
  • 45
0

If the outer objects property name is unknown, you will need to loop over the response object and test if there is a CLUSTER property inside.

const test1 = { 'ALICE': { CLUSTER: 1 } }
const test2 = { 'LOREM': { CLUSTER: 2 } }
const test3 = { 'IPSUM': { CLUSTER: 3 } }

// logs 1
for (const value of Object.values(test1)) {
   if (value.CLUSTER) {
      console.log(value.CLUSTER)
   }
}

// logs 2
for (const value of Object.values(test2)) {
   if (value.CLUSTER) {
      console.log(value.CLUSTER)
   }
}

// logs 3
for (const value of Object.values(test3)) {
   if (value.CLUSTER) {
      console.log(value.CLUSTER)
   }
}

This logic does not handle the case if you have multiple outer objects that contain CLUSTER, but you can easily add extra checks yourself.

Georgi B. Nikolov
  • 976
  • 2
  • 13
  • 24