1

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"]

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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)

2 Comments

thanks! I had a similar solution but was trying to see if was possible to accomplish this with .map or something else rather than 2 loops
Cool. Then you should go with the answer by@Addis and @ferhen. But I guess, if you are trying to use Object.keys and map for better time complexity, I think both approach would have same time complexity.
0

Using map

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.