Created
March 14, 2016 09:14
-
-
Save OlegLustenko/05b4b8503c54c2f7adc4 to your computer and use it in GitHub Desktop.
HTTP POST x-www-form-urlencode Lodash-practise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Задача: 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