首页 > 解决方案 > 将对象数组转换为列表数组

问题描述

对象数组如下所示:

[
    {
        "Type": "Location",
        "Name": "Water",
    },
    {
        "Type": "Location",
        "Coordinates": [
            {
                "Lat": 57.94182777439993,
                "Long": 79.50404114815193
            },
            {
                "Lat": 31.209277877460135,
                "Long": 78.80122177677728
            },
            {
                "Lat": 31.35950051982242,
                "Long": 105.15694820332524
            },
            {
                "Lat": 58.17432360099434,
                "Long": 105.42050546759074
            }
        ],
        "Name": "Water",
    },
    {
        "Type": "Location",
        "Coordinates": [
            {
                "Lat": 58.72972797827911,
                "Long": 76.90570777266291
            },
            {
                "Lat": 29.54717721331581,
                "Long": 76.37859324413196
            },
            {
                "Lat": 30.460511875130663,
                "Long": 105.19418747049103
            },
            {
                "Lat": 59.71902258556691,
                "Long": 106.7755310560839
            }
        ],
        "Type": "Location",
    }
]

注意:某些对象将没有坐标。

需要将它们转换为列表数组,看起来像,

            [
        [
              [80.2, 114.5],
              [67.8, 118.5],
              [69.8, 209.5],
              [82.8, 212.5],
        ],
    [
              [80.2, 114.5],
              [67.8, 118.5],
              [69.8, 209.5],
              [82.8, 212.5],
            ]
    ]

[经纬度]

我试过了,

const arrList = resp.data.data.map((coords) => {
          coords.Coordinates.map((coord) => {
            return [coords.Lat, coords.Long];
          });
        });
        console.log("ArrList:", arrList);

但不起作用。

标签: javascriptarrays

解决方案


你只需要你的地图回调来返回新的数组条目

const arrObj = [{"Lat":68.40928899869893,"Long":39.548560173006884},{"Lat":45.35600542155823,"Long":32.5203664592608},{"Lat":48.94054322456003,"Long":102.45089391103468},{"Lat":70.14969277620159,"Long":96.8283389400378}]

const arrList = arrObj.map(({ Lat, Long }) => [ Lat, Long ])
/* or more verbosely
arrObj.map(coords => {
  return [ coords.Lat, coords.Long ]
})
*/

console.log(arrList)
.as-console-wrapper { max-height: 100% !important; }


推荐阅读