0

I have a group of objects like this

         {
           'name'   :'Andrew',
           'gender' :'Male',
           'dob'    :'12/12/1991'
         },

         {
           'name'   :'Robby',
           'gender' :'Male',
           'dob'    :'12/12/1996'
         },

How do I convert this to an array of objects? For example

myArray:Array<any>= [
          {
              'name'   :'Andrew',
              'gender' :'Male',
              'dob'    :'12/12/1991'
          },

          {
               'name'   :'Robby',
               'gender' :'Male',
               'dob'    :'12/12/1996'
          },
     ]

I'm expecting group of objects to be converted into Array of objects. How do I achieve this in Typescript?

5
  • the first example is not a valid struture in js.. Commented Jan 11, 2017 at 14:27
  • myObj doesn't seem to be a valid object Commented Jan 11, 2017 at 14:27
  • 1
    The first snippet of yours isn't a valid js code. You must have key to value, and you have only values... Commented Jan 11, 2017 at 14:28
  • @yarons I'm getting data from backed as objects in the form of { }. I want to put these in an array. Commented Jan 11, 2017 at 14:30
  • @NitzanTomer I'm getting data from the backed as group of objects. I want to put all these in an array Commented Jan 11, 2017 at 14:32

2 Answers 2

3

The data that you're getting, if it's a valid json should look like this:

"key1": {
    'name'   :'Andrew',
    'gender' :'Male',
    'dob'    :'12/12/1991'
},
"key2": {
    'name'   :'Robby',
    'gender' :'Male',
    'dob'    :'12/12/1996'
}
...

If you have that in a variable then:

let json = that json strucutre
let objs = Object.keys(json).map(key => json[key]);
Sign up to request clarification or add additional context in comments.

Comments

0

There are many approaches, but a basic viable option is to use a for-in loop to populate an array, like so:

myArray = [] for (anObject in myObjects) { myArray.push(anObject) }

2 Comments

This will fetch only keys, not both keys and values
It is an array of objects. If you need to display the keys then use Object.keys.

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.