-
Notifications
You must be signed in to change notification settings - Fork 0
/
object-flat.js
39 lines (37 loc) · 895 Bytes
/
object-flat.js
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
const user = {
id: 1,
name: "mrkmx",
languages: ['en', 'ru'],
contact: {
email: 'test@example.com',
phone: null,
social: {
linkedin: "@mrkmx-dev",
},
},
};
function flattenObj(obj, parentKey, result = {}) {
Object.entries(obj).forEach(([key, value]) => {
const newKey = parentKey ? `${parentKey}_${key}` : key
if (Array.isArray(value)) {
result[newKey] = value.toString()
} else if (typeof value === 'object' && value !== null) {
flattenObj(value, newKey, result)
} else {
result[newKey] = value
}
})
return result
}
console.log(flattenObj(user))
/**
* Output:
* {
* id: 1,
* name: 'mrkmx',
* languages: 'en,ru',
* contact_email: 'test@example.com',
* contact_phone: null,
* contact_social_linkedin: '@mrkmx-dev'
* }
*/