How to change JSON keys in JavaScript

Changing the keys in an object in JavaScript can be problematic. In this blog, we will show you how to do this in JavaScript in 2 different ways. With and without external dependencies.

Segun Adebayo

Kevin Peters


A banner that shows kebab-case with an arrow

The simplest way to do the conversion in JavaScript is to use the script in the following section. The only thing you have to change is the changeCaseOfKey function. For that we have other pre-defined scripts later with the most common conversions.

1const changeCaseOfKey = key => {
2  // Here you can change the keys, if you are interested in different
3  // functionalities, scroll down in the article
4  return key.split("_").join("-");
7const isObject = o => {
8  return o === Object(o) && !Array.isArray(o) && typeof o !== "function";
11const changeCase = entity => {
12  if (entity === null) return entity;
14  if (isObject(entity)) {
15    const changedObject = {};
16    Object.keys(entity).forEach(originalKey => {
17      const newKey = changeCaseOfKey(originalKey);
18      changedObject[newKey] = changeCase(entity[originalKey]);
19    });
20    return changedObject;
21  } else if (Array.isArray(entity)) {
22    return => {
23      return changeCase(element);
24    });
25  }
27  return entity;
30const sourceJson = '{"test_case":true}';
31const sourceObject = JSON.parse(sourceJson);
33const result = changeCase(sourceObject); // Will be { test-case: true }

Converting to specific case types

As you can see you can just use the function with changeCase(sourceObject) and pass your sourceObject. You have to write your own transformer, so please replace the changeCaseOfKey function to work in the way you want.

The question is how to implement the case conversion cases then. But that is a solved problem already. The great package change-case exist that you can use to change the individual case types. It is well-tested and used in many production applications like this one here.

Changing to camelCase

As we mentioned before we need to adjust changeCaseOfKey function to actually convert the key to camelCase. To code that ourself you can use the following snippet.

1const changeCaseOfKey = key => {
2  return key.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
3    if (+match === 0) return "";
4    return index === 0 ? match.toLowerCase() : match.toUpperCase();
5  });

Alternatively you can use a great package called change-case. It is a quite simple to use:

1const changeCase = require("change-case");
3const changeCaseOfKey = key => {
4  return changeCase.camelCase(key);

I would recommend to use this approach because it will help you to have a battle-tested solution.

Changing to snake_case

The other most common use case is to change the keys to snake_case. Of coure the package change-case is supporting this as well. But you can also copy the following snippet to change the case manually to snake_case. Simply replace the changeCaseOfKey implementation of the main script linked in the beginning of this article.

1const changeCaseOfKey = key => {
2  return key
3    .replace(/\W+/g, " ")
4    .split(/ |\B(?=[A-Z])/)
5    .map(word => word.toLowerCase())
6    .join("_");

This works for most of the scenarios, but let us follow the approach that change-case is exposing. The package is well-tested and is covering more edge cases with proper formatting.

1const changeCase = require("change-case");
3const changeCaseOfKey = key => {
4  return changeCase.snakeCase(key);

How does the main script work?

Now we take a look at how the main script is actually working. For that we need to understand some smaller functions first. The first function we will look at is the isObject.

1const changeCase = require("change-case");
3const changeCaseOfKey = key => {
4  return changeCase.snakeCase(key);

This function basically gets any parameter and will return true or false depending on if the parameter is an object or not. This is done by type-casting the object and check for equality. In cases like Maps or similar it will return false. Then it checks that it is also no Array and also no function. For these cases it can happen that Object casting is returning equality by type casting with Object(o) but with these extra checks we can assure that the object is an object.

Replacing a JSON or Object key

After that we have to take a look at the changeCase function. This is the main function for actually changing all the keys. So what are we doing when changing the keys of an object? Let us first look at a simple object in JavaScript.

1const simpleObject = {
2  firstKey: "some value",
3  secondKey: "some other value",

For these cases it is quite simple to change the keys. The only thing we have to do is iterate through the keys and change them. This is the first problem we need to solve and it is solved already in the code in the initial script. If you check the first if branch after checking if the entity is an object you will find the following code.

1const changedObject = {};
2Object.keys(entity).forEach(originalKey => {
3  const newKey = changeCaseOfKey(originalKey);
4  changedObject[newKey] = changeCase(entity[originalKey]);

What this code is doing: It creates a temporary object, then iterates through the keys of the original object called entity and applies the changeCaseOfKey function to the key, and rewrites the value to it. When rewriting the the value it applies the main function to change an object again. Why? It is called recursion. This is working quite nicely because it will basically run through the object nicely for each branch. This algorithm is also called Depth-first search (DFS). But this would go endless if there would not be a stop condition right? So the changeCase has an if condition as we learned. First it checks if the entity is an object, then if it is an array and otherwise it returns the entity. And exactly this is the stop condition. It will go through the whole branches of the object until there is nothing to visit and change anymore.

An edge case are Arrays of course. It can happen that arrays appear in an object like shown in the following snippet.

1const objectArray = {
2  firstKey: "some value",
3  secondKey: [
4    {
5      firstNestedKey: "firstNestedValue",
6    },
7    {
8      secondNestedKey: {
9        deeplyNestedKey: "deeply nested value",
10      },
11    },
12  ],

As we can see we would need to iterate through the array as well. In our code this is done as well with the which basically goes over the array element by element and applies the same changeCase on each element. If it is an object it will change all keys, otherwise just return it or iterate throughout the array again.

Further Edge Cases

There are edge cases though. This script does not cover Maps or any other kind of more complex data structures. But this can be extended in the if-else block. Just add a condition where you detect these things and change the keys somehow. Do not forget to apply the function recursively though.

More from

  • some text

    How to convert any string to camelCase in JavaScript

    Converting a string to camelCase in JavaScript (JS) can be quite tricky with all edge cases. This blog will show you how to handle the edge cases and even converting object keys.

    Segun Adebayo

    Kevin Peters


  • some text

    How to change JSON keys in JavaScript

    Changing the keys in objects in JavaScript objects is sometimes required. JavaScript mostly works with camelCase and transforming other case types is really helpful to make linters happy.

    Segun Adebayo

    Kevin Peters


  • some text

    What's the name for hyphen-separated case?

    For the hyphen-separated case there are multiple names: kebab-case, hyphen-case, slug-case and many other options... But what is the right one to choose. This article will help you to make a decision.

    Segun Adebayo

    Kevin Peters


  • some text

    Why we love our tech stack

    The reasons why we love our technology stack at are quite diverse. Read it here and gather insightful statistics about which technologies were used and why you should use them too.

    Segun Adebayo

    Kevin Peters


This site is using cookies to personalize content and adverts, to provide social media features and to analyse traffic.