数组以分离对象

时间:2018-06-23 07:01:19

标签: javascript node.js

我想将下面的数组转换为提到的单独对象。这些是来自twitter的多边形坐标。我正在获取鸣叫位置,并希望将其存储在单独的对象中的某个位置。但是此数组来自Twitter API并没有什么不同。

<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 个答案:

答案 0 :(得分:1)

您可以使用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);

答案 1 :(得分:1)

使用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);

答案 2 :(得分:1)

您可以使用map将数组数组转换为对象数组。

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