📌  相关文章
📜  将嵌套的 json 转换为查询字符串 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:32.578000             🧑  作者: Mango

代码示例1
var isObj = function(a) {
  if ((!!a) && (a.constructor === Object)) {
    return true;
  }
  return false;
};
var _st = function(z, g) {
  return "" + (g != "" ? "[" : "") + z + (g != "" ? "]" : "");
};
var fromObject = function(params, skipobjects, prefix) {
  if (skipobjects === void 0) {
    skipobjects = false;
  }
  if (prefix === void 0) {
    prefix = "";
  }
  var result = "";
  if (typeof(params) != "object") {
    return prefix + "=" + encodeURIComponent(params) + "&";
  }
  for (var param in params) {
    var c = "" + prefix + _st(param, prefix);
    if (isObj(params[param]) && !skipobjects) {
      result += fromObject(params[param], false, "" + c);
    } else if (Array.isArray(params[param]) && !skipobjects) {
      params[param].forEach(function(item, ind) {
        result += fromObject(item, false, c + "[" + ind + "]");
      });
    } else {
      result += c + "=" + encodeURIComponent(params[param]) + "&";
    }
  }
  return result;
};

var data = {
  users: [{
      "name": "jeff",
      "tasks": [
        "Do one thing",
        "Do second thing"
      ]
    },
    {
      "name": "rick",
      "tasks": [
        "Never gonna give you up",
        "Never gonna let you down"
      ]
    }
  ]
}

document.write(fromObject(data));
 Run code snippet