为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法将包含数组的对象键转换为对象?

有没有办法将包含数组的对象键转换为对象?

九州编程 2022-10-08 17:52:45
这是我当前的对象:{"or_11[and_3][gt@last_closed_sr]":"2019-06-18"}我希望它看起来像:{  "or_11": {    "and_3": {      "gt@last_closed_sr": "2019-06-18",    }  }}做这个的最好方式是什么?
查看完整描述

2 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

一般来说,对格式不佳的数据的答案是修复格式化程序,而不是实现解析器。但是,我使用过像这样对数据进行编码的系统,所以这里有一个解析器。


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;

}



查看完整回答
反对 回复 2022-10-08
?
慕容708150

TA贡献1831条经验 获得超4个赞

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)


查看完整回答
反对 回复 2022-10-08
  • 2 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信