Skip to content

Commit

Permalink
Merge pull request #12 from canjs/arr2
Browse files Browse the repository at this point in the history
Encode objects within arrays to include indices
  • Loading branch information
matthewp authored Dec 14, 2018
2 parents e7f7d38 + f0c60b2 commit 83f5ac1
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 83f5ac1

Please sign in to comment.