将字符串转换为数组并在javascript

时间:2017-07-16 13:57:27

标签: javascript arrays

我正在将字符串转换为数组,但我需要在结果中添加标题。请帮忙:

// Get all coordinates from interface and pass it to an array
var latidudes_from_db = Array.from(document.querySelectorAll(".a"), input => input.value);
var longitudes_from_db = Array.from(document.querySelectorAll(".b"), input => input.value);

strings = latidudes_from_db.map((lat, i) => [lat, 
                                             longitudes_from_db[i]].join());
var markers = JSON.parse("[" + strings + "]");
console.log(markers);

输出我得到:

       0:-1.951
       1:30.095
       2:-1.942
       3:30.095

输出我希望:

[ 
  {
    "latitude": '0:-1.951',
    "longitude": '1:30.095'
  },
  {
    "latitude":  '2:-1.942',
    "longitude": '3:30.095'
  }
]

3 个答案:

答案 0 :(得分:0)

// Get all coordinates from interface and pass it to an array
   var latidudes_from_db = [ '1' , '2' ]
 var longitudes_from_db = ['3','4']

var markers = latidudes_from_db.map((lat, i) => {
  return {
   latitude: lat,
   longitude: longitudes_from_db[i]
   };
});
console.log(markers);

您可以返回

,而不是在[lat, longitudes_from_db[i]].join()函数中返回map
{
"latitude" : lat,
"longitude" : longitudes_from_db[i]
}

答案 1 :(得分:0)

嗯,如果你想从数组中创建它,我想我们可以使用map()函数并使用条件。

我在这里为您制作示例代码。



var markers = [
	"0:-1.951",
  "1:30.095",
  "2:-1.942",
  "3:30.095"
];

var newArr = [];
var obj = {};

markers.map(function(marker, index){
  if (index % 2 == 0) {
    obj.latitude = marker
  } else {
    obj.longitude = marker
  }
  
  if (Object.keys(obj).length == 2) {
    newArr.push(obj);
    obj = {}
  }
})
console.log(newArr)




好的,我希望它可以解决你的问题:D

答案 2 :(得分:0)

您可以在latitudes_from_db上映射时构建对象:

var latitudes_from_db = [-1.951, -1.942];
var longitudes_from_db = [30.095, 30.095];

console.log(
    latitudes_from_db.map((lat, i) => ({
        latitude: lat,
        longitude: longitudes_from_db[i]
    }))
);