626
626

Reputation: 1159

Iterate object keys and get inner object's keys into one array

I'm trying to get the keys of Object.keys all into one array but am having some difficulty.

Currently Im trying this but I get an array of each of the Object keys Object.keys(myObject).map(x=>Object.keys(myObject[x]))

Object:

    {
   "a1G0R000002Sv15UAC":{
      "a1K0R000000ytEsUAI":{ <---
         "test2_2":"test2"
      }
   },
   "a1G0R000002SvdYUAS":{
      "a1K0R000000yu8EUAQ":{ <---
         "test2_2":"test2"
      },
      "a1K0R000000ytEsUAI":{ <---
         "string_1":"test"
      }
   },
   "a1G0R000002T4NIUA0":{
      "a1K0R000000ytEsUAI":{ <---
         "string_1":"test"
      }
   }
}

Desired array: ["a1K0R000000ytEsUAI","a1K0R000000yu8EUAQ","a1K0R000000ytEsUAI","a1K0R000000ytEsUAI"]

Upvotes: 1

Views: 47

Answers (3)

Addis
Addis

Reputation: 2530

You can use flat to convert the result into a single array"

const myObject =     {
   "a1G0R000002Sv15UAC":{
      "a1K0R000000ytEsUAI":{ 
         "test2_2":"test2"
      }
   },
   "a1G0R000002SvdYUAS":{
      "a1K0R000000yu8EUAQ":{ 
         "test2_2":"test2"
      },
      "a1K0R000000ytEsUAI":{ 
         "string_1":"test"
      }
   },
   "a1G0R000002T4NIUA0":{
      "a1K0R000000ytEsUAI":{ 
         "string_1":"test"
      }
   }
}

const keys = Object.keys(myObject).map(key => Object.keys(myObject[key])).flat();

console.log(keys)

Upvotes: 1

ferhen
ferhen

Reputation: 653

Using map

Object.entries(myObject).map(x => Object.keys(x[1])).flat()

Upvotes: 0

Shubhaw Kumar
Shubhaw Kumar

Reputation: 721

You will have to use 2 for..in loops. In simple words, for..in loop iterates over the key of an object. For more information, you can have a look at MDN doc.

const originalObject = {
   "a1G0R000002Sv15UAC":{
      "a1K0R000000ytEsUAI":{ 
         "test2_2":"test2"
      }
   },
   "a1G0R000002SvdYUAS":{
      "a1K0R000000yu8EUAQ":{ 
         "test2_2":"test2"
      },
      "a1K0R000000ytEsUAI":{ 
         "string_1":"test"
      }
   },
   "a1G0R000002T4NIUA0":{
      "a1K0R000000ytEsUAI":{ 
         "string_1":"test"
      }
   }
}

const desiredArray = []

for (let i in originalObject) {
  for(let j in originalObject[i]) {
    desiredArray.push(j)
  }
}

console.log(desiredArray)

Upvotes: 0

Related Questions