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

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

如何規范化具有特殊字符屬性的 JS 對象

如何規范化具有特殊字符屬性的 JS 對象

HUH函數 2023-05-25 16:48:12
大家好,我正在做一個項目,我得到了一個看起來像這樣的對象:{  "userChoice[language]": "en",  "userChoice[responses][favColor]": "black",  "userChoice[responses][favCity]": "new york",}我該如何規范化?這樣我就可以訪問我需要的屬性了嗎?
查看完整描述

2 回答

?
元芳怎么了

TA貢獻1798條經驗 獲得超7個贊

這是規范化對象的 es5 方法


function normalisedObject(object) {

    var normalised = {};

    for (var key in object) {

        //regex to capture all [.*] groups

        var matches = key.match(/\[(.*?)\]/g);

        if (matches) {

            var temp = normalised;

            while (matches.length > 0) {

                //get first key and replace []

                var newKey = matches[0].replace(/\[|\]/g, "");

                if (matches.length !== 1) {

                    //keep traverse if the left over keys are greater than 1

                    temp = temp[newKey] || (temp[newKey] = {}); //assign empty object

                } else {

                    temp[newKey] = object[key];

                }

                //poll

                matches.shift();

            }

        }

    }

    return normalised;

}


//example

const t1 = performance.now();

var object = {

    "userChoice[language]": "en",

    "userChoice[responses][favColor]": "black",

    "userChoice[responses][favCity]": "new york"

};

var normalised = normalisedObject(object);

const t2 = performance.now();

console.log(`Operation took ${t2 - t1}ms`);

console.log(normalised);


查看完整回答
反對 回復 2023-05-25
?
四季花海

TA貢獻1811條經驗 獲得超5個贊

當對象的鍵不允許您使用簡單的點表示法時,即obj.property,您可以使用方括號表示法,例如


const lang = obj["userChoice[language]"]

但我有一種感覺,你真的想把那個物體變成類似這個的東西


{

  userChoice: {

    language: "en",

    responses: {

      favColor: "black",

      favCity: "new york"

    }

  }

}

如果是這種情況,您需要將對象條目(鍵/值對)減少到一個新對象,解析出關鍵路徑并構建新的內部對象


const obj = {

  "userChoice[language]": "en",

  "userChoice[responses][favColor]": "black",

  "userChoice[responses][favCity]": "new york",

}


const t1 = performance.now()


const normalised = Object.entries(obj).reduce((c, [ key, val ]) => {

  // get the key parts as a path array

  const path = key.replace(/]/g, "").split(/\[/)

  

  // pop the last property for assigning the value later

  const prop = path.pop()

  

  // determine the inner-most object by path

  const inner = path.reduce((o, k) => {

    // create a new object if it doesn't exist

    return o[k] ?? (o[k] = {})

  }, c)

  

  // assign the value

  inner[prop] = val

  

  return c

}, {})


const t2 = performance.now()


console.info(normalised)

console.log(`Operation took ${t2 - t1}ms`)

.as-console-wrapper { max-height: 100% !important; }

請注意,如果您開始將任何數組屬性放入 eg 中userChoice[foo][0],這將不起作用。



查看完整回答
反對 回復 2023-05-25
  • 2 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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