-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
对象扁平化 #77
Comments
递归法: let arr = [1, [2, [3, 4, 5]]]; function flatten(arr){ |
function flattenObject(obj, prefix = '', res = {}) {
for (let key in obj) {
let newKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null && !(obj[key] instanceof Date)) {
flattenObject(obj[key], newKey, res);
} else {
res[newKey] = obj[key];
}
}
return res;
}
function flattenObjectStack(obj) {
const stack = [[[], obj]];
const result = {};
while (stack.length > 0) {
const [keys, value] = stack.pop();
if (typeof value === 'object' && value !== null && !(value instanceof Date)) {
for (let k in value) {
stack.push([[...keys, k], value[k]]);
}
} else {
result[keys.join('.')] = value;
}
}
return result;
} |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: