简体   繁体   中英

picking two elements from JSON array and adding to a new json array

I have a JSON Array which looks like this on Stringify:

 [{"lat":40,"lng":90},{"lat":41,"lng":91},{"lat":42,"lng":92},{"lat":43,"lng":94}]

and so on ( Actual array will have more entries). I want to pick two elements at a time, create a JSON array (exact same format as above) and plot each as a line on google Maps.

Code I wrote goes like this. json is what I get on using JSON.parse whose stringify version is mentioned above.

var x=[];
for(var i=0;i<json.length/2;i+=2)
{
x=json[i];
x+=json[i+1];
//var y=JSON.parse(x);
console.log(x);
}

As expected I get a [object Object][object Object] output. Can I directly use this to plot? I don't think so because I get this if I stringify x

 "[object Object][object Object]"

I think I'm doing this wrong or missing out on some basic thing. Not that well-versed in Javascript. Please help. Thanks.

You need to use push method to add values in array.

var x=[];
for(var i=0;i<json.length/2;i+=2)
{
x.push(json[i]);
x.push(json[i+1]);
console.log(x);
}

And you can use the resultant array like this

var lat = x[0].lat;
var lng = x[0].lng;

Or you can loop over array as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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