Last active
June 4, 2022 04:27
-
-
Save ichengzi/fa90fede6c7ce91bbb083ea2e5466a38 to your computer and use it in GitHub Desktop.
flat deep js object
This file contains 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
// https://gist.github.com/ichengzi/fa90fede6c7ce91bbb083ea2e5466a38 | |
const entry = { | |
a: { | |
b: { | |
c: { | |
dd: "abcdd" | |
} | |
}, | |
d: { | |
ee: "abdee" | |
}, | |
f: 'af', | |
} | |
}; | |
// 递归写法, 深度优先, 所有叶子结点从左到右逐个打印 | |
function flatObj1(obj, preKey = '', result = {}) { | |
for (const key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
if (typeof obj[key] === 'object') { | |
flatObj1(obj[key], `${preKey}${key}.`, result); | |
} else { | |
result[`${preKey}${key}`] = obj[key]; | |
} | |
} | |
} | |
return result; | |
} | |
// 迭代写法, 广度优先,叶子结点逐层从左向右打印; | |
// 所以输出顺序和递归方式不一样,如果有顺序要求,需要重新排序 | |
function flatObj2(obj) { | |
const result = {}; | |
const queue = Object.entries(obj); | |
while (queue.length > 0) { | |
const [key, value] = queue.shift(); | |
for (const [k, v] of Object.entries(value)) { | |
if (typeof v === 'object') { | |
queue.push([`${key}.${k}`, v]); | |
} else { | |
result[`${key}.${k}`] = v; | |
} | |
} | |
} | |
return result; | |
} | |
console.log(flatObj1(entry)); | |
console.log(flatObj2(entry)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment