How to convert group of objects into an Array in Typescript

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?

2 answers

  • answered 2017-01-11 14:25 Phil Cap

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

  • answered 2017-01-11 14:25 Nitzan Tomer

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