Skip to content

Commit

Permalink
Encode objects within arrays to include indices
Browse files Browse the repository at this point in the history
This makes it so that objects within arrays include the index.

```
{items: [{name:'one'}, {name:'two'}]}
```

becomes

```
items[0][name]=one&items[1][name]=two
``

Note that non-objects will not include the index. This is to match
jQuery's encoder.

```
{items: [{name:'one'}, {name:'two'}]}
```

Still becomes

```
items[]=one&items[]=two
```

Fixes #11
  • Loading branch information
matthewp committed Dec 14, 2018
1 parent e7f7d38 commit f0c60b2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
16 changes: 15 additions & 1 deletion can-param-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ QUnit.test("can-param", function(){
age: {
or: [ {lte: 5}, null ]
}
}), encodeURI("age[or][][lte]=5&age[or][]=null"));
}), encodeURI("age[or][0][lte]=5&age[or][1]=null"));

QUnit.deepEqual(param({
"undefined": undefined,
Expand All @@ -22,3 +22,17 @@ QUnit.test("can-param", function(){
"false": false
}),"undefined=undefined&null=null&NaN=NaN&true=true&false=false","true, false, undefined, etc");
});

QUnit.test("Encoding arrays of objects includes indices", function(){
var object = {items: [{name:'one'}, {name:'two'}]};
var out = param(object);

QUnit.equal(out, "items%5B0%5D%5Bname%5D=one&items%5B1%5D%5Bname%5D=two");
});

QUnit.test("Encoding array of primitives does not include indices", function() {
var object = {items: ['one', 'two']};
var out = param(object);

QUnit.equal(out, "items%5B%5D=one&items%5B%5D=two");
});
5 changes: 4 additions & 1 deletion can-param.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ var namespace = require("can-namespace");
function buildParam(prefix, obj, add) {
if (Array.isArray(obj)) {
for (var i = 0, l = obj.length; i < l; ++i) {
buildParam(prefix + '[]', obj[i], add);
var inner = obj[i];
var shouldIncludeIndex = typeof inner === 'object';
var arrayIndex = shouldIncludeIndex ? '[' + i + ']' : '[]';
buildParam(prefix + arrayIndex, inner, add);
}
} else if ( obj && typeof obj === "object" ) {
for (var name in obj) {
Expand Down

0 comments on commit f0c60b2

Please sign in to comment.