jQuery-展平一个JavaScript对象以作为querystring传递

我有一个JavaScript对象,我需要将其展平为一个字符串,以便可以作为querystring传递,我该怎么做? 即:

{ cost: 12345, insertBy: 'testUser' }将成为data

我不能为此调用使用jQuery AJAX调用,我知道我们可以使用该对象并将对象传递为data,但在这种情况下不可以。 不过,使用jQuery展平到对象可以。

谢谢。

Saxman asked 2019-12-23T19:33:02Z
11个解决方案
81 votes

这是非jQuery版本:

function toQueryString(obj) {
    var parts = [];
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
        }
    }
    return parts.join("&");
}
Tim Down answered 2019-12-23T19:33:35Z
66 votes

您想要data

var str = $.param({ cost: 12345, insertBy: 'testUser' });
// "cost=12345&insertBy=testUser"

请注意,这是jQuery内部用于序列化作为data参数传递的对象的函数。

lonesomeday answered 2019-12-23T19:33:15Z
36 votes

我的ES6版本(纯Javascript,没有jQuery):

function toQueryString(paramsObject) {
  return Object
    .keys(paramsObject)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(paramsObject[key])}`)
    .join('&')
  ;
}
Michaël Perrin answered 2019-12-23T19:33:54Z
16 votes

如果您已经在使用其中一个库,这是另一个使用lodash或下划线的非jQuery版本:

var toQueryString = function(obj) {
  return _.map(obj,function(v,k){
    return encodeURIComponent(k) + '=' + encodeURIComponent(v);
  }).join('&');
};
Guy answered 2019-12-23T19:34:14Z
15 votes

尝试使用$.param()方法:

var result = $.param({ cost: 12345, insertBy: 'testUser' });
Darin Dimitrov answered 2019-12-23T19:34:34Z
15 votes

这是一个古老的问题,但是在Google搜索的顶部,因此为了完整性起见,我添加了这个问题。

如果1)您不想使用jQuery,但2)您想将嵌套对象隐藏到查询字符串中,然后(根据Tim Down和Guy的答案构建),请使用以下命令:

function toQueryString(obj, urlEncode) {
    //
    // Helper function that flattens an object, retaining key structer as a path array:
    //
    // Input: { prop1: 'x', prop2: { y: 1, z: 2 } }
    // Example output: [
    //     { path: [ 'prop1' ],      val: 'x' },
    //     { path: [ 'prop2', 'y' ], val: '1' },
    //     { path: [ 'prop2', 'z' ], val: '2' }
    // ]
    //
    function flattenObj(x, path) {
        var result = [];

        path = path || [];
        Object.keys(x).forEach(function (key) {
            if (!x.hasOwnProperty(key)) return;

            var newPath = path.slice();
            newPath.push(key);

            var vals = [];
            if (typeof x[key] == 'object') {
                vals = flattenObj(x[key], newPath);
            } else {
                vals.push({ path: newPath, val: x[key] });
            }
            vals.forEach(function (obj) {
                return result.push(obj);
            });
        });

        return result;
    } // flattenObj

    // start with  flattening `obj`
    var parts = flattenObj(obj); // [ { path: [ ...parts ], val: ... }, ... ]

    // convert to array notation:
    parts = parts.map(function (varInfo) {
        if (varInfo.path.length == 1) varInfo.path = varInfo.path[0];else {
            var first = varInfo.path[0];
            var rest = varInfo.path.slice(1);
            varInfo.path = first + '[' + rest.join('][') + ']';
        }
        return varInfo;
    }); // parts.map

    // join the parts to a query-string url-component
    var queryString = parts.map(function (varInfo) {
        return varInfo.path + '=' + varInfo.val;
    }).join('&');
    if (urlEncode) return encodeURIComponent(queryString);else return queryString;
}

使用方式如下:

console.log(toQueryString({
    prop1: 'x',
    prop2: {
        y: 1,
        z: 2
    }
}, false));

哪个输出:

prop1=x&prop2[y]=1&prop2[z]=2
Jrop answered 2019-12-23T19:35:08Z
4 votes

通用JavaScript:

function toParam(obj) {
  var str = "";
  var seperator = "";
  for (key in obj) {
    str += seperator;
    str += enncodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
    seperator = "&";
  }
  return str;
}


toParam({ cost: 12345, insertBy: 'testUser' })
"cost=12345&insertBy=testUser"
Jim Blackler answered 2019-12-23T19:35:27Z
4 votes

另一个版本:

function toQueryString(obj) {
    return Object.keys(obj).map(k => {
      return encodeURIComponent(k) + "=" + encodeURIComponent(obj[k])
    })
    .join("&");
}
blablabla answered 2019-12-23T19:35:47Z
3 votes
var myObj = { cost: 12345, insertBy: 'testUser' },
    param = '',
    url   = 'http://mysite.com/mypage.php';    

for (var p in myObj) {
  if (myObj.hasOwnProperty(p)) {
    param += encodeURIComponent(p) + "=" + encodeURIComponent(myObj[p]) + "&";
  }
}

window.location.href = url + "?" + param;
mVChr answered 2019-12-23T19:36:03Z
1 votes

你可以用这个

function serialize(obj)
{
    let str = []

    for(var p in obj)
    {
      if(obj.hasOwnProperty(p)) str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
    }

    return str.join('&')
}

在此链接上尝试JSFiddle [https://jsfiddle.net/yussan/kwmnkca6/]

yussan answered 2019-12-23T19:36:27Z
1 votes

ES6版本的Jrop的答案(还解析嵌套的参数)

const toQueryString = (obj, urlEncode = false) => {
  if (!obj) return null;
  const flattenObj = (x, path = []) => {
    const result = [];
    Object.keys(x).forEach((key) => {
      if (!Object.prototype.hasOwnProperty.call(x, key)) return;
      const newPath = path.slice();
      newPath.push(key);
      let vals = [];
      if (typeof x[key] === 'object') {
        vals = flattenObj(x[key], newPath);
      } else {
        vals.push({ path: newPath, val: x[key] });
      }
      vals.forEach((v) => {
        return result.push(v);
      });
    });
    return result;
  };

  let parts = flattenObj(obj);
  parts = parts.map((varInfo) => {
    if (varInfo.path.length === 1) {
      varInfo.path = varInfo.path[0]; // eslint-disable-line no-param-reassign
    } else {
      const first = varInfo.path[0];
      const rest = varInfo.path.slice(1);
      varInfo.path = `${first}[${rest.join('][')}]`; // eslint-disable-line no-param-reassign
    }
    return varInfo;
  });

  const queryString = parts.map((varInfo) => {
    return `${varInfo.path}=${varInfo.val}`;
  }).join('&');
  if (urlEncode) {
    return encodeURIComponent(queryString);
  }
  return queryString;
};
Mythical Fish answered 2019-12-23T19:36:47Z
translate from https://stackoverflow.com:/questions/5505085/flatten-a-javascript-object-to-pass-as-querystring