-
-
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
逆对象扁平 #78
Comments
function unflattenObject(data) {
let result = {};
for (let key in data) {
let keys = key.split('.');
keys.reduce((r, k, i, a) => {
return r[k] || (r[k] = isNaN(a[i + 1]) ? (a.length - 1 === i ? data[key] : {}) : []);
}, result);
}
return result;
}
let testObj = {
'a.b.c': 1,
'd.e': [2,3],
};
console.log(unflattenObject(testObj)); // 输出:{ a: { b: { c: 1 } }, d: { e: [2,3] } } |
function unflattenObject(data) {
let obj = {}
for (const key in data) {
let keys = key.split('.');
let tmp = obj;
for (let i = 0; i < keys.length; i++) {
if (i === keys.length - 1){
tmp[keys[i]] = data[key];
break;
}
if (!Object.hasOwnProperty.call(tmp, keys[i])) {
tmp[keys[i]] = {};
}
tmp = tmp[keys[i]];
}
}
return obj
}
let testObj = {
'a.b.c': 1,
'd.e': [2,3],
};
console.log(unflattenObject(testObj)); // 输出:{ a: { b: { c: 1 } }, d: { e: [2,3] } } |
|
export default function unsquashObject(obj) {
const res = {}; // Initialize an empty result object to store the reconstructed nested structure
// Iterate over each flattened key-value pair in the input object
for (const flatKey in obj) {
const value = obj[flatKey]; // Get the value associated with the current flattened key
const keys = flatKey.split("."); // Split the flattened key by "." to get the individual keys for nesting
let current = res; // Start from the root of the result object
// Iterate through each key in the path, building out the nested structure
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
// Check if the current level of nesting already contains the key
if (i === keys.length - 1) {
// If it's the last key in the path, assign the value
current[key] = value;
} else {
// If it's not the last key, ensure the next level of nesting exists
if (!Object.hasOwn(current, key)) {
current[key] = {}; // If the key does not exist, create an empty object
}
current = current[key]; // Move deeper into the nested structure
}
}
}
return res; // Return the fully reconstructed nested object
} |
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: