首页 > 解决方案 > 有没有办法将包含数组的对象键转换为对象?

问题描述

这是我当前的对象:

{"or_11[and_3][gt@last_closed_sr]":"2019-06-18"}

我希望它看起来像:

{
  "or_11": {
    "and_3": {
      "gt@last_closed_sr": "2019-06-18",
    }
  }
}

做这个的最好方式是什么?

标签: javascriptangularjs

解决方案


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)


推荐阅读