将新字段添加到 Javascript 获取响应对象

Add a new field to Javascript Fetch response object

我正在制作带有标记的地图。我通过获取 google api url 获得了地理坐标数据。但是对于标记,我需要来自其他地方的额外信息。是否可以将此附加信息附加到我从获取 url 获得的响应中?非常感谢!
代码:

var location = "Seattle";
var username = "Test user";
var time = "8th March 2017";

function toMap(location, username, time) {
    if (location.length > 0) { 
        var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&key=Your_API_Key";
        fetch(googleURL)
            .then(function(response) {

     // Can I add "location", "username", and "time" to the response result here 
     //  before returning it?????

                return response.json();
             })
            .then(addMarker);
    }
}

当然你可以在响应对象中添加任何你想要的字段

假设

fetch(googleURL)
            .then(function(response) {
               //set these values to anything
               response.location = "";
               response.username = "";
               response.time = "";

               return response.json();
             })
            .then(addMarker);

Body.json() The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with an object literal containing the JSON data.

您可以将 .then() 链接到 .json(),在 .then() 处理程序调用中设置属性,javascript 普通对象的值,return 对象作为参数

  fetch(googleURL)
  .then(function(response) {

    // Can I add "location", "username", and "time" to the response result here 
    //  before returning it?????

    return response.json().then(function(json) {
      json.location = "abc";
      json.username = "def";
      json.time = 123;
      return json;
    });
  })
  .then(addMarker);

因为 response.json() returns Promise of Object,你可以在另一个 then() 回调中完成。

var location = "Seattle";
var username = "Test user";
var time = "8th March 2017";

function toMap(location, username, time) {
    if (location.length > 0) { 
        var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&key=Your_API_Key";
        fetch(googleURL)
            .then(function(response) {
                return response.json();
            })
            .then(function(json) {
                json.location = location;
                json.username = username;
                json.time = time;
                return json;
            })
            .then(addMarker);
    }
}