我們正在使用 vue-i18n 并在 js 變數中維護我們的訊息。這會導致深度嵌套的物件或鍵/值對。
const messages = {
en: {
message: {
page1: {
title: "Some title",
button: {
title: "Foo",
},
subpage: {
...
}
},
...
},
},
de: {...},
};
正如你所看到的,如果沒有適當的排序,這個檔案會很混亂。我的想法是按鍵按字母順序對整個檔案進行排序。
是否有可用于此的演算法/代碼?還是我必須自己寫?
uj5u.com熱心網友回復:
你可以做一些遞回,比如:
我用下面的答案寫了order函式
const order = (unordered) => Object.keys(unordered).sort().reduce(
(obj, key) => {
obj[key] = unordered[key];
return obj;
}, {}
);
const message = {
fr: {
message: "Bonjour",
a: 1
},
en: {
message: "Hello",
a: {
c: 1,
b: 2
}
},
es: "Hola"
}
const sortObjectDeeply = (object) => {
for (let [key, value] of Object.entries(object)) {
if (typeof(value) === "object") {
object[key] = sortObjectDeeply(value)
}
}
return order(object)
}
console.log(sortObjectDeeply(message))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466633.html
標籤:javascript
