F
F
Formula_12018-02-21 16:14:08
JavaScript
Formula_1, 2018-02-21 16:14:08

How to form an array?

There is an array containing objects:

[
    {ID: "123", lat: "55.680024", lng: "37.558505"},
    {ID: "123", lat: "55.680024", lng: "37.558505"},
    {ID: "987", lat: "55.783861", lng: "37.536533"},
    {ID: "987", lat: "55.783861", lng: "37.536533"}
]

Please tell me how to collect another array of the form from this array:
[
    {
        ID: "123",
        Coords: [
            {lat: "55.680024", lng: "37.558505"},
            {lat: "55.680024", lng: "37.558505"}
        ]
    },
    {
        ID: "987",
        Coords: [
            {lat: "55.783861", lng: "37.536533"},
            {lat: "55.783861", lng: "37.536533"}
        ]
    }
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2018-02-21
@Formula_1

var arr = [
    {ID: "123", lat: "55.680024", lng: "37.558505"},
    {ID: "123", lat: "55.680024", lng: "37.558505"},
    {ID: "987", lat: "55.783861", lng: "37.536533"},
    {ID: "987", lat: "55.783861", lng: "37.536533"}
];
console.log( convert(arr));

function convert(arr){
  var newarr = [];
  arr.map((e)=>{
      for(var i = 0;i < newarr.length;i++)
        if(newarr[i].ID == e.ID){
          newarr[i].Coords.push({lat:e.lat,lng:e.lng});
          return;
         }
        newarr.push({ID:e.ID,Coords:[{lat:e.lat,lng:e.lng}]});
  });
return newarr;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question