簡體   English   中英

遞歸地將對象字段從 camelCase 轉換為 UPPERCASE

[英]Recursively convert an object fields from camelCase to UPPERCASE

我試圖遞歸地將對象字段從駝峰式轉換為大寫。

由於某種原因它不起作用,我在stackoverflow中嘗試了許多不同的方法。

感謝所有的幫助,謝謝。

 const o = {
  KeyFirst: "firstVal",
  KeySecond: [
    {
      KeyThird: "thirdVal",
    },
  ],
  KeyFourth: {
    KeyFifth: [
      {
        KeySixth: "sixthVal",
      },
    ],
  },
};
function renameKeys(obj) {
  return Object.keys(obj).reduce((acc, key) => {
    const value = obj[key];
    const modifiedKey = `${key[0].toLowerCase()}${key.slice(1)}`;
    if (Array.isArray(value)) {
      return {
        ...acc,
        ...{ [modifiedKey]: value.map(renameKeys) },
      };
    } else if (typeof value === "object") {
      return renameKeys(value);
    } else {
      return {
        ...acc,
        ...{ [modifiedKey]: value },
      };
    }
  }, {});
}

console.log(renameKeys(o));

您可以遞歸循環對象並將鍵轉換為大寫。

 const o = { KeyFirst: { KeySecond: "secondVal" }, KeyThird: [{ KeyFourth: "fourthVal" }], KeyFifth: { KeySixth: [{ KeySeventh: "seventhVal" }], }, }; function renameKeys(obj) { if (Array.isArray(obj)) { return obj.map((o) => renameKeys(o)); } else if (typeof obj === "object" && obj !== null) { return Object.entries(obj).reduce( (r, [k, v]) => ({ ...r, [k.toUpperCase()]: renameKeys(v) }), {} ); } else { return obj; } } console.log(renameKeys(o));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM