0

I have tried to recursively convert an object fields from camelCase to UPPERCASE.

For some reason it wont work, I have tried many different ways from here in stackoverflow.

Would apprecaite for all the help, thanks.

 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));
Oscar
  • 27
  • 4
  • 1
    `toLowerCase` is changing the key to lower case. Consider using [`toUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) – evolutionxbox Jun 15 '22 at 13:04

1 Answers1

2

You can recursively loop over the object and transform the keys to be uppercase.

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));
SSM
  • 2,855
  • 1
  • 3
  • 10