[英]How to push json item to array?
我有以下 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
},
我试过:
var str = JSON.stringify(<?php echo $contents; ?>, null, 2);
$.each (str, function (i) {
console.log(str[i]["lat"]);
});
但我做错了。 我知道我不是在推动,但循环是错误的。
我需要遍历这些项目,并且需要将lat+lng
推送到单个数组,例如
const coords: ["lat, lng", "lat, lng"]
如果您要迭代它,请不要将 JSON 字符串化。
如果您想使用JSON.parse
因为它可能来自 PHP 作为字符串。
像这样:
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);
});
你可以这样试试。
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"]
如果您将 JSON 作为字符串,那么您可以使用JSON.parse("yourString")
来获取您的 JSON 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.