-1

With jQuery.param i can do:

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};
var recursiveEncoded = $.param( myObject );
var recursiveDecoded = decodeURIComponent( $.param( myObject ) );

recursiveDecoded; // "a[]=foo&a[]=bar&b[]=1&b[]=2&b[]=3"

But how to got:

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};

from "a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3" ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
bux
  • 7,087
  • 11
  • 45
  • 86

1 Answers1

1

Try

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};

var json = JSON.stringify(myObject);
var _arr = decodeURIComponent($.param(JSON.parse(json)));
var arr = JSON.parse(JSON.stringify(_arr.split("=").join("&").split("&")));
var obj = [];
var tempObj = [];
var tempVals = [];    
$.each(arr, function(index, value) {
  if ( /\[/.test(value) ) {
    var props = value.split(/\[|\]/).slice(0, 2);
    tempObj.push(props);        
  };
    if ( !/\[/.test(value) ) {
    var vals = Number(value);
    tempVals.push(vals);
  };      
});    
$.when($.each(tempObj, function(index, value) {
   value.push(tempVals[index])
}))
.done(function(data) {
  $.each(data, function(index, value) {
    obj.push(value.filter(Boolean))
  });
});    
console.log(obj);

Edit (update)

Utilizing a forked version (without $.browser, which returned Uncaught TypeError: Cannot read property 'msie' of undefined at jsfiddle) of jquery BBQ $.deparam() method , try

    var myObject = {
      a: {
        one: 1,
        two: 2,
        three: 3
      },
      b: [ 1, 2, 3 ]
    };

    var p = decodeURIComponent( $.param( myObject ));
    var d = $.deparam( p );
      console.log( p, d ); 
   // a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3 
   // Object {a: Object, b: Array[3]}

jsfiddle http://jsfiddle.net/guest271314/6P7tf/

guest271314
  • 1
  • 15
  • 104
  • 177