代码之家  ›  专栏  ›  技术社区  ›  rob.m

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

  •  0
  • rob.m  · 技术社区  · 5 年前

    我有以下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"]
    
    2 回复  |  直到 5 年前
        1
  •  0
  •   Alan Geo Mathew    5 年前

    你可以这样试试。

    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对象。

        2
  •  0
  •   Marc Farias Jones    5 年前

    如果你想用的话 JSON.parse

    像这样的:

    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);
    });