【问题标题】:Google Apps Script to Output a JSON Array into a rows将 JSON 数组输出到行中的 Google Apps 脚本
【发布时间】:2020-06-23 17:59:10
【问题描述】:

对不起,我刚学了应用脚本,我的英语不好。在Google app脚本上,以json数组为例,如何得到itemAitemC的输出?

{
    "items":[
        {
            "itemA":123,
            "itemB":"qwe",
            "itemC":"asd"
        },
        {
            "itemA":456,
            "itemB":"rty",
            "itemC":"fgh"
        },
        {
            "itemA":789,
            "itemB":"uio",
            "itemC":"jkl"
        }
    ]
}

我想要这样的输出:

123, asd
456, fgh
789, jkl

非常感谢您的帮助。

【问题讨论】:

    标签: javascript json google-apps-script google-sheets


    【解决方案1】:

    这个脚本给出了你想要的输出。
    满意吗?

    var json = {
      "items": [{
          "itemA": 123,
          "itemB": "qwe",
          "itemC": "asd"
        },
        {
          "itemA": 456,
          "itemB": "rty",
          "itemC": "fgh"
        },
        {
          "itemA": 789,
          "itemB": "uio",
          "itemC": "jkl"
        }
      ]
    }
    var output_text = "";
    json.items.forEach(function(item) {
      output_text += item.itemA + ", " + item.itemC + "\n";
    });
    console.log(output_text);

    【讨论】:

    • delete 就地删除。如果意图是修改原始对象,forEach 更适合迭代。
    • @Antoni,谢谢你的回答,请检查我的问题的更新
    【解决方案2】:

    试试下面的代码:

    let obj = {
        "items":[
            {
                "itemA":123,
                "itemB":"qwe",
                "itemC":"asd"
            },
            {
                "itemA":456,
                "itemB":"rty",
                "itemC":"fgh"
            },
            {
                "itemA":789,
                "itemB":"uio",
                "itemC":"jkl"
            }
        ]
    };
    
    function genOutput() {
      var output = obj.items.map( item => [item.itemA,item.itemC] );
      console.log( output );
    };
    

    运行函数genOutput,会得到如下输出:

    [ [ 123, 'asd' ], [ 456, 'fgh' ], [ 789, 'jkl' ] ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多