javascript - 有没有办法将包含数组的对象键转换为对象?
问题描述
这是我当前的对象:
{"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)
推荐阅读
- azure-devops - 当作为复杂对象类型参数的一部分传递并与另一个对象合并时,无法识别 Devops yaml 字符串数组
- excel - 在 Excel 中将总计运行到一个值,重置累计总计,然后分组?
- node.js - 在带有 M1 芯片的 MacOS 11.6.1 上的 npm 全局安装出现问题
- r - 我需要进行数据预处理以执行以下操作:
- flutter - 在 vsCode 中运行 dart 终端
- python - 测试功能获取多个文件
- php - 如何选择使用 Laravel Sanctum 进行身份验证?
- python - Kraken API - 帐户余额请求返回 Invalid Nonce
- javascript - 如何避免 .map 跳过空格?
- logback - java 17 logback SMTPAppender: AuthenticationFailedException: 220 准备启动 TLS