亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法將包含數組的對象鍵轉換為對象?

有沒有辦法將包含數組的對象鍵轉換為對象?

九州編程 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 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號