【问题标题】:Converting 2d array to Object将二维数组转换为对象
【发布时间】:2020-01-24 01:14:22
【问题描述】:

我有这个二维数组

"coordinates" : [ 
            [ 
                [ 
                    41.5311338460033, 
                    -8.61901849508286
                ], 
                [ 
                    41.5311338460033, 
                    -8.61851692199707
                ], 
                [ 
                    41.5312944769825, 
                    -8.61851692199707
                ], 
                [ 
                    41.5312944769825, 
                    -8.61901849508286
                ], 
                [ 
                    41.5311338460033, 
                    -8.61901849508286
                ]
            ]
        ]

我正在尝试将其转换为

const paths = [
      { lat: 41.53113384600326, lng: -8.619018495082855 },
      { lat: 41.53113384600326, lng: -8.61851692199707 },
      { lat: 41.53129447698251, lng: -8.61851692199707 },
      { lat: 41.53129447698251, lng: -8.619018495082855 },
      { lat: 41.53113384600326, lng: -8.619018495082855 }
    ];

我正在尝试做这个方法

let test = this.props.places.places.map(place => {
      place.location.coordinates.map((c,i) => {
        console.log('MAP TEST', c);
        return {
          lat: c[i],
          lng: c[i]
        };
      });
    });

console.log 从我的两个文档中返回两个位置,但是当我进行控制台测试时,我收到了 num。 任何人都知道如何将该数组转换为 latlng 对象?

【问题讨论】:

    标签: javascript arrays node.js reactjs


    【解决方案1】:

    您以错误的方式访问数组。

    如果是二维数组,可以尝试使用.flat

    const obj = {
        "coordinates": [
            [
                [41.5311338460033, -8.61901849508286],
                [41.5311338460033, -8.61851692199707],
                [41.5311338460033, -8.61851692199707],
                [41.5311338460033, -8.61901849508286],
                [41.5311338460033, -8.61901849508286],
            ],
            [
                [41.5311338460033, -8.61901849508286],
                [41.5311338460033, -8.61851692199707],
                [41.5311338460033, -8.61851692199707],
                [41.5311338460033, -8.61901849508286],
                [41.5311338460033, -8.61901849508286],
            ],
        ]
    }
    
    const paths = obj.coordinates.map(cord => cord.map(x => ({lat: x[0], lng: x[1]}))).flat()
    
    console.log(paths)

    对于你的情况,你应该这样做

    let test = this.props.places.places.map(place => {
        // return addded
        return place.location.coordinates.map((c, i) => {
            console.log('MAP TEST', c);
            return c.map(x => ({
                lat: x[i],
                lng: x[i]
            }))
        }).flat();
    });
    

    【讨论】:

    • 记住坐标是一个来自我的数据库的数组,我有更多来自其他文档的坐标,我想通过
    • 你在做我在这里做不到的 const obj
    • @FCorreia const obj 只是向您展示逻辑的示例。请检查我的编辑,我在您的示例中添加了代码。不要忘记在.mapreturn
    猜你喜欢
    • 2020-11-10
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    相关资源
    最近更新 更多