【问题标题】:Recursively convert an object fields from camelCase to UPPERCASE递归地将对象字段从 camelCase 转换为 UPPERCASE
【发布时间】:2022-06-15 20:57:44
【问题描述】:

我尝试将对象字段从 camelCase 递归转换为 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));

【问题讨论】:

  • toLowerCase 正在将密钥更改为小写。考虑使用toUpperCase

标签: javascript


猜你喜欢
  • 2020-05-03
  • 2010-11-05
  • 1970-01-01
  • 2021-09-18
  • 2017-05-20
  • 2021-01-09
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
相关资源
最近更新 更多