1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
test('オブジェクトの展開', () => {
const targetObject = {
input: {
person: {
id: 1,
name: 'hoge',
},
test: ['foo', 'bar', 'baz'],
},
}
const actual = extractor([], targetObject).map(format)
const expected = [
'input.person.id=1',
'input.person.name="hoge"',
'input.test=["foo","bar","baz"]',
]
expect(actual).toStrictEqual(expected)
console.log(actual)
})
const extractor = (prevKeys: string[], obj: any): [string[], any][] => {
if (typeof obj === 'object' && !Array.isArray(obj)) {
return Object.entries(obj).flatMap(([k, v]) => extractor([...prevKeys, k], v))
} else {
return [[prevKeys, obj]]
}
}
const format = ([k, v]: [string[], any]): string => `${k.join('.')}=${formatValue(v)}`
const formatValue = (v: any): string => {
if (typeof v === 'string') return `"${v}"`
if (Array.isArray(v)) return `[${v.map(formatValue).join(',')}]`
return v
}
export {}
|