Ehsan Ehsan - 5 months ago 27
AngularJS Question

How to convert nested object to query string in Angularjs

I want to convert this object:

$scope.foo = {
bar: {
baz: 'foobarbaz'
}
}


to

foo[bar][baz]=foobarbaz


query string.

Also how to convert

$scope.fields = ['id', 'name', 'created_at']


to

fields[]=id&fields[]=name&fields[]=created_at`


Is there any library or function in Angularjs to do this job?

Answer

No need to write those serializers yourself, Angular has the one built-in for you. imply inject $httpParamSerializerJQLike service and use it:

$scope.foo = {
  foo: {
    bar: {
      baz: 'foobarbaz'
    }
  }
};

$scope.fields = {
  fields: ['id', 'name', 'created_at']
};

console.log( $httpParamSerializerJQLike($scope.foo) );
// => "foo[bar][baz]=foobarbaz"

console.log( $httpParamSerializerJQLike($scope.fields) );
// => "fields[]=id&fields[]=name&fields[]=created_at"

// (output shown URL-decoded)