-
Notifications
You must be signed in to change notification settings - Fork 55
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
18 additions
and
38 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,23 @@ | ||
|
||
|
||
// messages are in the form of Record<string, string>. | ||
// if the key of the message contains `path1.path2`, it should be converted to a corresponding object | ||
// similarly, if the key of the message contains `path1.path2[number]`, it should be converted to a corresponding object with an array | ||
// e.g. { 'path1.path2': 'value', 'path1.path3[0]': 'value1', 'path1.path3[1]': 'value2' } should be converted to { path1: { path2: 'value', path3: ['value1', 'value2'] } } | ||
export function transformMessages (messages) { | ||
// e.g. { 'path1.path2': 'value', 'path1.path3': 'value' } => { path1: { path2: 'value', path3: 'value' } } | ||
export function transformMessages(messages) { | ||
const transformedMessages = {}; | ||
Object.keys(messages).forEach((key) => { | ||
for (const key in messages) { | ||
const path = key.split('.'); | ||
const value = messages[key]; | ||
let current = transformedMessages; | ||
for (let i = 0; i < path.length; i++) { | ||
const pathPart = path[i]; | ||
if (pathPart.endsWith(']')) { | ||
// array | ||
const arrayPath = pathPart.split('['); | ||
const arrayName = arrayPath[0]; | ||
const arrayIndex = parseInt(arrayPath[1].replace(']', '')); | ||
if (!current[arrayName]) { | ||
current[arrayName] = []; | ||
} | ||
if (i === path.length - 1) { // last part of the path | ||
current[arrayName][arrayIndex] = messages[key] || undefined; | ||
} else { | ||
if (!current[arrayName][arrayIndex]) { | ||
current[arrayName][arrayIndex] = {}; | ||
} | ||
current = current[arrayName][arrayIndex]; | ||
} | ||
const pathKey = path[i]; | ||
if (i === path.length - 1) { | ||
current[pathKey] = value; | ||
} else { | ||
// object | ||
if (i === path.length - 1) { // last part | ||
current[pathPart] = messages[key] || undefined | ||
} else { | ||
if (!current[pathPart]) { | ||
current[pathPart] = {}; | ||
} | ||
current = current[pathPart]; | ||
if (!current[pathKey]) { | ||
current[pathKey] = {}; | ||
} | ||
current = current[pathKey]; | ||
} | ||
} | ||
}); | ||
} | ||
return transformedMessages; | ||
} |