![](/img/trans.png)
[英]How to convert a array containing object string to regular key object pair?
[英]Is there a way to convert an object key containing an array to an object?
這是我當前的 object:
{"or_11[and_3][gt@last_closed_sr]":"2019-06-18"}
我希望它看起來像:
{
"or_11": {
"and_3": {
"gt@last_closed_sr": "2019-06-18",
}
}
}
做這個的最好方式是什么?
let str = '"or_11[and_3][gt@last_closed_sr]":"2019-06-18"'; let first = str.replace(/"/g, '').match(/\w+/)[0]; let pattern = /\[(.+?)\]/g; let matches = []; let match; while(match = pattern.exec(str)) { matches.push(match[1]) } let val = str.replace(/"/g, '').split(':')[1]; let obj = { [first]: { [matches[0]]: { [matches[1]]: val } } } console.log(obj)
一般來說,對格式不佳的數據的答案是修復格式化程序,而不是實現解析器。 但是,我使用過像這樣對數據進行編碼的系統,所以這里有一個解析器。
function parseSquareSeparatedData(data) {
const result = {};
Object.keys(data).forEach((key) => {
const keyParts = key.replace(/]/g, "").split("[");
const last = keyParts.pop();
let resultPointer = result;
keyParts.forEach((keyPart) => {
if (!(keyPart in resultPointer)) {
resultPointer[keyPart] = {};
}
resultPointer = resultPointer[keyPart];
})
resultPointer[last] = input[key];
})
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.