skip to Main Content

I want to convert below array to mentioned separate objects. These are polygon coordinates from twitter. I am getting the tweet locations and want to store somewhere in a separate object. But this array is coming from Twitter API is little different.

<script>
[
    [76.70535130773267, 30.70314577305184],
    [76.70535130773267, 30.70314577305184],
    [76.70535130773267, 30.70314577305184],
    [76.70535130773267, 30.70314577305184]
]
[
    [76.515454, 30.569094],
    [76.860158, 30.569094],
    [76.860158, 30.938966],
    [76.515454, 30.938966]
]

[{
        lat: 30.569094,
        lng: 76.515454
    },
    {
        lat: 30.569094,
        lng: 76.860158
    },
    {
        lat: 30.938966,
        lng: 76.860158
    },
    {
        lat: 30.938966,
        lng: 76.515454
    }
], [{
        lat: 30.70314577305184,
        lng: 76.70535130773267
    },
    {
        lat: 30.70314577305184,
        lng: 76.70535130773267
    },
    {
        lat: 30.70314577305184,
        lng: 76.70535130773267
    },
    {
        lat: 30.70314577305184,
        lng: 76.70535130773267
    }
]

3

Answers


  1. You can use Array.reduce()

    var arr = [
        [76.70535130773267, 30.70314577305184],
        [76.70535130773267, 30.70314577305184],
        [76.70535130773267, 30.70314577305184],
        [76.70535130773267, 30.70314577305184]
    ];
    
    var result = arr.reduce((a,curr)=>{
      a.push({
        "lat" : curr[1],
        "lng" : curr[0]
      });
      return a;
    },[]);
    
    console.log(result);
    Login or Signup to reply.
  2. Use Array.map

    let arr = [[[76.70535130773267, 30.70314577305184],[76.70535130773267, 30.70314577305184],[76.70535130773267, 30.70314577305184],[76.70535130773267, 30.70314577305184]],[[76.515454, 30.569094],[76.860158, 30.569094],[76.860158, 30.938966],[76.515454, 30.938966]]];
    let result = arr.map(a => a.map(([lng, lat]) => ({lat, lng})));
    console.log(result);
    Login or Signup to reply.
  3. You can use map to convert the array of arrays into an array of objects.

    var arr = [
      [76.70535130773267, 30.70314577305184],
      [76.70535130773267, 30.70314577305184],
      [76.70535130773267, 30.70314577305184],
      [76.70535130773267, 30.70314577305184]
    ]
    
    var result = arr.map(([lat, lng]) => ({lat,lng}))
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search