2 回答

TA貢獻1798條經驗 獲得超7個贊
這是規范化對象的 es5 方法
function normalisedObject(object) {
var normalised = {};
for (var key in object) {
//regex to capture all [.*] groups
var matches = key.match(/\[(.*?)\]/g);
if (matches) {
var temp = normalised;
while (matches.length > 0) {
//get first key and replace []
var newKey = matches[0].replace(/\[|\]/g, "");
if (matches.length !== 1) {
//keep traverse if the left over keys are greater than 1
temp = temp[newKey] || (temp[newKey] = {}); //assign empty object
} else {
temp[newKey] = object[key];
}
//poll
matches.shift();
}
}
}
return normalised;
}
//example
const t1 = performance.now();
var object = {
"userChoice[language]": "en",
"userChoice[responses][favColor]": "black",
"userChoice[responses][favCity]": "new york"
};
var normalised = normalisedObject(object);
const t2 = performance.now();
console.log(`Operation took ${t2 - t1}ms`);
console.log(normalised);

TA貢獻1811條經驗 獲得超5個贊
當對象的鍵不允許您使用簡單的點表示法時,即obj.property,您可以使用方括號表示法,例如
const lang = obj["userChoice[language]"]
但我有一種感覺,你真的想把那個物體變成類似這個的東西
{
userChoice: {
language: "en",
responses: {
favColor: "black",
favCity: "new york"
}
}
}
如果是這種情況,您需要將對象條目(鍵/值對)減少到一個新對象,解析出關鍵路徑并構建新的內部對象
const obj = {
"userChoice[language]": "en",
"userChoice[responses][favColor]": "black",
"userChoice[responses][favCity]": "new york",
}
const t1 = performance.now()
const normalised = Object.entries(obj).reduce((c, [ key, val ]) => {
// get the key parts as a path array
const path = key.replace(/]/g, "").split(/\[/)
// pop the last property for assigning the value later
const prop = path.pop()
// determine the inner-most object by path
const inner = path.reduce((o, k) => {
// create a new object if it doesn't exist
return o[k] ?? (o[k] = {})
}, c)
// assign the value
inner[prop] = val
return c
}, {})
const t2 = performance.now()
console.info(normalised)
console.log(`Operation took ${t2 - t1}ms`)
.as-console-wrapper { max-height: 100% !important; }
請注意,如果您開始將任何數組屬性放入 eg 中userChoice[foo][0]
,這將不起作用。
添加回答
舉報