序列化对象数组

时间:2014-10-27 15:32:55

标签: javascript jquery angularjs underscore.js

我有一个查询Rest API的函数。函数调用如下:

var filters = [
    {field: "TestField", "params[value]": "VIDEO"},
    {field: "TestField2", "params[value]": "IMAGE"},
];

this.query({limit: 10, text:"Test", filters: filters});

我想构建一个类似于:

的查询字符串
?limit=10&text="Test"&filters[0].field=TestField&filters[0].params[value]=VIDEO&filters[1].field=TestField2&filters[1].params[value]=IMAGE

在JavaScript中关于过滤器阵列的最佳/最快方法是什么?

1 个答案:

答案 0 :(得分:0)

Array.prototype.map是你的朋友:

var filters = [
    {field: "TestField", "params[value]": "VIDEO"},
    {field: "TestField2", "params[value]": "IMAGE"},
];

var qs = filters.map(function(filter,i){
    return "filters[" + i + "].field=" +
            encodeURIComponent(filter.field) +
            "&filters[" + i + "].params[value]=" +
            encodeURIComponent(filter["params[value]"]);
}).join("&");