From f0c60b2117dda498dfc541f1670961efc17c60e6 Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Fri, 14 Dec 2018 12:42:20 -0500 Subject: [PATCH] Encode objects within arrays to include indices 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 --- can-param-test.js | 16 +++++++++++++++- can-param.js | 5 ++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/can-param-test.js b/can-param-test.js index e854fef..674022c 100644 --- a/can-param-test.js +++ b/can-param-test.js @@ -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, @@ -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"); +}); diff --git a/can-param.js b/can-param.js index 5b3135e..7715656 100644 --- a/can-param.js +++ b/can-param.js @@ -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) {