繁体   English   中英

如何将数组数组转换为对象数组

[英]How can I convert an array of arrays into an array of objects

我使用 mapbox,我可以在其中绘制一条路线,该路线为我提供坐标,然后将其放入数组中。 我需要将这个数组数组转换成一个对象数组,这样我就可以通过 post 将它发送到后端。 但我可以弄清楚如何做到这一点。 这就是我的数组现在的样子,里面有几个坐标:

[1

我想要的是这样的东西,我不是 100% 确定这是否是一个对象 tbh :):

[{
    "latitude": 52.25155727661456,
    "longitude": 6.148788223460181
}, {
    "latitude": 52.25179372912126,
    "longitude": 6.147507915253847
}, {
    "latitude": 52.25205645297342,
    "longitude": 6.147157440051708
}, {
    "latitude": 52.25237609814013,
    "longitude": 6.147178897723827
}]

我怎样才能将我拥有的数组转换为上面的数组? 我需要这个,所以我可以通过 post 函数将它发送到后端 API。 我尝试使用这样的东西:

for (var i = 0, len = coords.length; i < len; i++) {
    jsonObj['latitude'] = coords[i];
}

但它并没有像我希望的那样工作。 这是我的代码的一点点,我将值放入我的数组中: 在此处输入图像描述

这就是我尝试将数据发送到服务器的方式:

const xhr = new XMLHttpRequest();
                // listen for `load` event
                xhr.onload = () => {
                    // print JSON response
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // parse JSON
                        //const response = JSON.parse(xhr.responseText);
                        console.log(xhr.responseText);
                    }
                };

                // open request
                xhr.open('POST', saveAllMeasurement);

                // set `Content-Type` header
                xhr.setRequestHeader('Content-Type', 'application/json');

                // send rquest with JSON payload
                xhr.send(coordsObj);

您可以使用map和解构将子数组转换为对象:

 let coordinates = [ [52.25155727661456, 6.148788223460181], [52.25179372912126, 6.147507915253847], [52.25205645297342, 6.147157440051708], [52.25237609814013, 6.147178897723827] ]; let result = coordinates.map(([longitude, latitude]) => ({longitude, latitude})); console.log(result);

使用map返回一个对象数组

 const coords = [ [31.00283837, -5.3838382], [2.52346457, 8.23472645] ]; const jsonCoords = coords.map(coord => ({ latitude: coord[0], longitude: coord[1] })) console.log(jsonCoords)

使用 for 循环:

 let cords = [ [6.148788223460181, 52.25155727661456], [8.148788223460181, 12.25155727661456], [3.148788223460181, 16.25155727661456], [8.148788223460181, 17.25155727661456], ] let jsonObj = []; for(let i = 0; i < cords.length; i ++) { jsonObj.push({ latitude: cords[i][1], longitude: cords[i][0] }) } console.log(jsonObj)

获取您的起始数组,然后将其映射到一个新的对象数组中

 const originalArray = [ [6.148788223460181,52.25155727661456] , [6.148788223460181,52.25155727661456] , [6.148788223460181,52.25155727661456] ] console.log('@array', originalArray) const newArray = originalArray.map(element => ({latitude: element[1], longitude: element[0]})) console.log('@newArray',newArray)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM