简体   繁体   English

从JSON数组中选择两个元素,然后添加到新的json数组中

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

I have a JSON Array which looks like this on Stringify: 我有一个在Stringify上看起来像这样的JSON数组:

 [{"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. 我想一次选择两个元素,创建一个JSON数组(与上述格式完全相同),然后在Google Maps上将它们绘制成一行。

Code I wrote goes like this. 我写的代码是这样的。 json is what I get on using JSON.parse whose stringify version is mentioned above. json是我使用JSON.parse ,上面提到了它的字符串化版本。

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. 不出所料,我得到了[object Object][object Object]输出。 Can I directly use this to plot? 我可以直接使用它来绘图吗? I don't think so because I get this if I stringify x 我不这样认为,因为如果我将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. 并不精通Javascript。 Please help. 请帮忙。 Thanks. 谢谢。

You need to use push method to add values in array. 您需要使用push方法在数组中添加值。

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 你可以像这样使用结果array

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

Or you can loop over array as needed. 或者你可以loop根据需要在阵。

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

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