Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* ========== Vanilla JS ========== */
- const applyValue = (existing, newValue) =>
- !existing
- ? newValue
- : !Array.isArray(existing)
- ? [existing, newValue]
- : [...existing, newValue];
- const paramsToObject = (params) => {
- const res = {};
- for (const [name, val] of searchParams) {
- Object.assign(res, {
- [name]: applyValue(res[name], val)
- });
- }
- return res;
- };
- const search = '?day=Friday&item=Eat&item=Sleep';
- const searchParams = new URLSearchParams(search);
- console.log(paramsToObject(searchParams));
- /* ========== Lodash ========== */
- const { assign, isArray, reduce } = _;
- const applyValue = (existing, newValue) =>
- !existing
- ? newValue
- : !isArray(existing)
- ? [existing, newValue]
- : [...existing, newValue];
- const paramsToObject = (params) =>
- reduce([...searchParams.entries()], (res, [name, val]) =>
- assign(res, { [name]: applyValue(res[name], val) }), {});
- const search = '?day=Friday&item=Eat&item=Sleep';
- const searchParams = new URLSearchParams(search);
- console.log(paramsToObject(searchParams));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement