I have the following json:
[
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "08:54:00 AM",
"Plastic": 0.156,
"Metal": 0.321,
"Paper": 0.098,
"Glass": 0.085
},
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "10:15:23 AM",
"Plastic": 0.078,
"Metal": 0.652,
"Paper": 0.085,
"Glass": 0.078
},
I tried:
var str = JSON.stringify(<?php echo $contents; ?>, null, 2);
$.each (str, function (i) {
console.log(str[i]["lat"]);
});
But I'm doing it wrong. I know I'm not pushing but the looping is wrong.
I need to loop over those items and I need lat+lng
to be pushed to a single array like
const coords: ["lat, lng", "lat, lng"]
Don't Stringify the JSON if you're going to iterate over it.
if anything you may want to use JSON.parse
as it could be coming from PHP as a string.
something like this:
var array = <?php echo $contents; ?>;
/// or if it's coming as a string from php
var array = JSON.parse(<?php echo $contents; ?>);
array.forEach((thing) => {
coords.push({thing['lat'], thing['lng']});
console.log(thing.lat);
});
You can try like this.
var jsonObj = [
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "08:54:00 AM",
"Plastic": 0.156,
"Metal": 0.321,
"Paper": 0.098,
"Glass": 0.085
},
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "10:15:23 AM",
"Plastic": 0.078,
"Metal": 0.652,
"Paper": 0.085,
"Glass": 0.078
}];
var coords = jsonObj.map(function(item) {
return (item.Lat + "," + item.Lng);
});
console.log(coords); // ["39.21988,9.124741", "39.21988,9.124741"]
If you are having your JSON as a string, then you can use JSON.parse("yourString")
to get your JSON object.
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.