展平一个 javascript 对象以作为查询字符串传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5505085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:30:19  来源:igfitidea点击:

Flatten a javascript object to pass as querystring

javascriptjqueryjavascript-objectsflatten

提问by Saxman

I have a javascript object that I need to flatten into a string so that I can pass as querystring, how would I do that? i.e:

我有一个 javascript 对象,我需要将它压缩成一个字符串,以便我可以作为查询字符串传递,我该怎么做?IE:

{ cost: 12345, insertBy: 'testUser' }would become cost=12345&insertBy=testUser

{ cost: 12345, insertBy: 'testUser' }会成为 cost=12345&insertBy=testUser

I can't use jQuery AJAX call for this call, I know we can use that and pass the object in as databut not in this case. Using jQuery to flatten to object would be okay though.

我不能在这个调用中使用 jQuery AJAX 调用,我知道我们可以使用它并将对象传入 asdata但在这种情况下不能。不过,使用 jQuery 扁平化为对象是可以的。

Thank you.

谢谢你。

回答by Tim Down

Here's a non-jQuery version:

这是一个非 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("&");
}

回答by lonesomeday

You want jQuery.param:

你想要jQuery.param

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

Note that this is the function used internally by jQuery to serialize objects passed as the dataargument.

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

回答by Micha?l Perrin

My ES6 version (pure Javascript, no jQuery):

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

function toQueryString(paramsObject) {
  return Object
    .keys(paramsObject)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(paramsObject[key])}`)
    .join('&')
  ;
}

回答by Guy

Here is another non-jQuery version that utilizes lodash or underscore if you're already using one of those libraries:

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

var toQueryString = function(obj) {
  return _.map(obj,function(v,k){
    return encodeURIComponent(k) + '=' + encodeURIComponent(v);
  }).join('&');
};

^ I wrote that 5 years ago. An updated and more succinct version of this would now (Oct 2019) be:

^ 我5年前写的。更新和更简洁的版本现在(2019 年 10 月)是:

var input = { cost: 12345, insertBy: 'testUser' };
Object.entries(input)
  .map(([k,v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
  .join('&');
// cost=12345&insertBy=testUser

Check that the runtime that you're targeting supports Object.entries() or that you're using a transpiler like Babel or TypeScript if it doesn't.

检查您所针对的运行时是否支持 Object.entries() 或者您是否正在使用 Babel 或 TypeScript 之类的转译器(如果不支持)。

回答by Jrop

This is an old question, but at the top of Google searches, so I'm adding this for completeness.

这是一个老问题,但在谷歌搜索的顶部,所以我添加这个是为了完整性。

If 1) you don't want to user jQuery, but 2) you want to covert a nestedobject to a query string, then (building off of Tim Down and Guy's answers), use this:

如果 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;
}

Use like:

像这样使用:

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

Which outputs:

哪些输出:

prop1=x&prop2[y]=1&prop2[z]=2

回答by Darin Dimitrov

Try the $.param()method:

试试$.param()方法:

var result = $.param({ cost: 12345, insertBy: 'testUser' });

回答by Jim Blackler

General JavaScript:

通用 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"

回答by blablabla

Another version:

另一个版本:

function toQueryString(obj) {
    return Object.keys(obj).map(k => {
      return encodeURIComponent(k) + "=" + encodeURIComponent(obj[k])
    })
    .join("&");
}

回答by mVChr

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;

回答by yussan

you can use this

你可以用这个

function serialize(obj)
{
    let str = []

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

    return str.join('&')
}

try on JSFiddle on this link https://jsfiddle.net/yussan/kwmnkca6/

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