简体   繁体   English

如何将json项目推送到数组?

[英]How to push json item to array?

I have the following json:我有以下 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我需要遍历这些项目,并且需要将lat+lng推送到单个数组,例如

const coords: ["lat, lng", "lat, lng"]

Don't Stringify the JSON if you're going to iterate over it.如果您要迭代它,请不要将 JSON 字符串化。

if anything you may want to use JSON.parse as it could be coming from PHP as a string.如果您想使用JSON.parse因为它可能来自 PHP 作为字符串。

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.如果您将 JSON 作为字符串,那么您可以使用JSON.parse("yourString")来获取您的 JSON 对象。

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

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