-1

I have the following return from an API:

{
"0": {
    "lat": "-30.02897288697400000",
    "lng": "-51.22800440001900000"
},
"1": {
    "lat": "-30.02879088697400000",
    "lng": "-51.22803440001900000"
},
"2": {
    "lat": "-30.02846288697400000",
    "lng": "-51.22814140001900000"
},
"3": {
    "lat": "-30.02822088697400000",
    "lng": "-51.22821640001900000"
},
"4": {
    "lat": "-30.02760388697400000",
    "lng": "-51.22844040001900000"
}
 (...continues)

How do I map that into an Array to use it in my Angular app? So far I've tried creating an array of this object without luck:

export class MyClass {
  lat: string;
  lng: string;
}

and...

handleSuccessfulResponse(response) {
  this.myClass = response;
}

What am I doing wrong?

Daniel Fleck
  • 117
  • 2
  • 11
  • 1
    can you tell us the output you desire ? – Abdelrahman Hussien Sep 03 '20 at 18:55
  • 1
    i think what op means, is that he's getting an object returned with numeric keys, and wants to convert that to an array equivalent. – Brenden Sep 03 '20 at 18:57
  • Does this answer your question? [Converting a JS object to an array using jQuery](https://stackoverflow.com/questions/6857468/converting-a-js-object-to-an-array-using-jquery) (note that this question has answers which do not use jQuery) – Heretic Monkey Sep 03 '20 at 18:58
  • You can use `.map` to cast new MyClass objects for your result array, or an alternative is `Object.values(response)` – Hemant Halwai Sep 03 '20 at 18:58

2 Answers2

1

You could use method Objects.values() as follows:

const result = {
  "0": {
    "lat": "-30.02897288697400000",
    "lng": "-51.22800440001900000"
  },
  "1": {
    "lat": "-30.02879088697400000",
    "lng": "-51.22803440001900000"
  },
  "2": {
    "lat": "-30.02846288697400000",
    "lng": "-51.22814140001900000"
  },
  "3": {
    "lat": "-30.02822088697400000",
    "lng": "-51.22821640001900000"
  },
  "4": {
    "lat": "-30.02760388697400000",
    "lng": "-51.22844040001900000"
  }
};

const myArray = Object.values(result);
console.log(myArray);
uminder
  • 23,831
  • 5
  • 37
  • 72
0

you can use Object.values for this, find the snippet code for more details.

let obj={
"0": {
    "lat": "-30.02897288697400000",
    "lng": "-51.22800440001900000"
},
"1": {
    "lat": "-30.02879088697400000",
    "lng": "-51.22803440001900000"
},
"2": {
    "lat": "-30.02846288697400000",
    "lng": "-51.22814140001900000"
},
"3": {
    "lat": "-30.02822088697400000",
    "lng": "-51.22821640001900000"
}}

let arr=Object.values(obj);
console.log(arr)
Abdelrahman Hussien
  • 505
  • 2
  • 4
  • 17
  • I think you should map over the values and return a collection of MyClass instead of just values. of the object. – Brenden Sep 03 '20 at 19:09