简体   繁体   English

如何将数组拆分为使用javascript给出的格式?

[英]How to split array to a format as given using javascript?

My data is 我的数据是

["9.968034,77.906814", "8.699679,77.478347", "8.797406,80.895095"]

How can split this to 如何将其拆分为

[
    { lat: 9.968034, lng: 77.906814},
    { lat: 8.699679, lng: 77.478347},
    { lat: 8.797406, lng: 80.895095}
];

Please help me to have a solution... 请帮我解决问题...

I tried as 我尝试了

 var jArray = ["9.968034,77.906814", "8.699679,77.478347", "8.797406,80.895095"]; var temp = {}; for(var j=0; j<jArray.length;j++){ var tr = { 'lat' :jArray[j][1], 'lng' :jArray[j][0] } temp.push(tr); } console.log(temp) 

You can try this. 你可以试试看

With the help of map() and split() functions. 借助map()split()函数。

 let arr = ["9.968034,77.906814", "8.699679,77.478347", "8.797406,80.895095"] let op = arr.map(e => { let temp = e.split(','); return { lat:temp[0], lng: temp[1] }; }) console.log(op); 

You could split an destrucure the array. 您可以拆分一个解构数组。

 var data = ["9.968034,77.906814", "8.699679,77.478347", "8.797406,80.895095"], result = data.map(s => (([lat, lng]) => ({ lat, lng })) (s.split(',')) ); console.log(result); 

Javascript has a built in JSON parse for strings, which I think is what you have: Javascript具有针对字符串的内置JSON解析,我想这就是您拥有的:

var myObject = JSON.parse("my json string");

to use this with your example would be: 在您的示例中使用此代码将是:

var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
    var counter = jsonData.counters[i];
    console.log(counter.counter_name);
}

Try it, I hope it helps you. 尝试一下,希望对您有所帮助。

You could use map and ES2015 destructuring assignment like this: 您可以使用如下map和ES2015 解构分配

 let data = ["9.968034,77.906814", "8.699679,77.478347", "8.797406,80.895095"] let newArray = data.map(loc => { const [lat, lng] = loc.split(',') return { lat, lng } }) console.log(newArray) 

This will do it for you. 这将为您做到。

var arrayOfStrings = ["9.968034,77.906814", "8.699679,77.478347", "8.797406,80.895095"];
var arrayOfObjects = [];

for(var item = 0; item < arrayOfString.length; item++){
   var latlng = {};
   var splittedValues = arrayOfString[item].split(",");
   latlng["lat"] = splittedValues[0];
   latlng["long"] = splittedValues[1]
   arrayOfObjects.push(latlng);
}

console.log(arrayOfObjects);

Your loop is correct but you should split string by , delimiter using .split() to getting parts of string. 您的循环是正确的,但是您应该使用.split()分隔符使用分隔符分割字符串,以获取字符串的一部分。

 var jArray = ["9.968034,77.906814", "8.699679,77.478347", "8.797406,80.895095"]; var temp = []; for (var j=0; j<jArray.length;j++){ temp.push({ 'lat': jArray[j].split(',')[0], 'lng': jArray[j].split(',')[1] }); } console.log(temp); 

Also you can use foreach instead 你也可以用foreach代替

var temp = [];
jArray.forEach(function(item){
  temp.push({
    'lat' :item.split(',')[0],
    'lng' :item.split(',')[1]
  });
});

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

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