Skip to content

Instantly share code, notes, and snippets.

@OlegLustenko
Created March 14, 2016 09:14
Show Gist options
  • Select an option

  • Save OlegLustenko/05b4b8503c54c2f7adc4 to your computer and use it in GitHub Desktop.

Select an option

Save OlegLustenko/05b4b8503c54c2f7adc4 to your computer and use it in GitHub Desktop.
HTTP POST x-www-form-urlencode Lodash-practise
Задача: build_key_value
Flatten the given hash. This is how HTTP libraries pack data when POST requests are made using x-www-form-urlencoded.
Example: {"x[0]":"1","x[1]":"2","x[2]":"3"} == solution({"x":["1","2","3"]})
var _ = require('lodash')
module.exports = solution = (s, p) => {
var r = {};
_.forEach(s, (v, k) => {
if (_.isObject(v)) {
if (!p) {
r = _.merge(r, solution(v, k));
} else {
r = _.merge(r, solution(v, p + '[' + k + ']'));
}
} else {
if (!p) {
r[k] = v;
} else {
r[p + '[' + k + ']'] = v;
}
}
});
return r;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment