Skip to content

Instantly share code, notes, and snippets.

@tuscen
Last active January 5, 2016 03:15
Show Gist options
  • Select an option

  • Save tuscen/380409165bf0e0e4d6b4 to your computer and use it in GitHub Desktop.

Select an option

Save tuscen/380409165bf0e0e4d6b4 to your computer and use it in GitHub Desktop.
'use strict';
export default function flatten(obj) {
const pairs = Object.keys(obj).reduce((acc, key) => {
const pair = [key, obj[key]];
return acc.concat([pair]);
}, []);
return pairs.reduce((acc, [k, v]) => {
switch (typeof v) {
case 'object':
const newObj = Object.keys(v).reduce((acc, key) => {
return Object.assign(acc, { [`${k}[${key}]`]: v[key] });
}, {});
return Object.assign(acc, flatten(newObj))
default:
return Object.assign(acc, { [k]: v })
}
}, {});
}
'use strict';
import flatten from './flatten.js';
const testData = [
{
expected: {"x[0]": "1", "x[1]": "2", "x[2]": "3"},
arguments: {"x": ["1","2","3"]}
},
{
expected: {"a[d][0]": 1, "a[d][1]": 2},
arguments: {"a": {"d": [1, 2]}}
},
{
expected: {"a[b]": 3, "a[c]": 2, "a[d][0]": 1, "a[d][1]": 2, "x[0]": "1", "x[1]": "2", "x[2]": "3"},
arguments: {"a": {"b": 3, "c": 2, "d": [1, 2]}, "x": ["1", "2", "3"]}
},
{
expected: {"a[b]": 3},
arguments: {"a": {"b": 3}}
}
]
function test(testData) {
const test = testData.map(data => {
const result = solution(data.arguments);
return JSON.stringify(result) === JSON.stringify(data.expected);
}).map(result => result ? '.' : 'F').join('');
console.log(test);
}
test(testData); // => ....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment