JavaScript: Flattening JSON with custom separator

In this tutorial we will learn how to use a custom separator when flattening a JavaScript object with the flat package.

Introduction

In this tutorial we will learn how to use a custom separator when flattening a JavaScript object with the flat package.

Note that, by default, the “.” character is used as separator in the path of the property in the flattened object.

For an introductory tutorial on how to use the flat package to flatten an object, please check here.

The code

We will start by importing the flatten function from the flat package.

const flatten = require('flat').flatten;

After that we will define a JavaScript object to flatten. We will use the same one from the previous tutorial, since it contains some nested objects and arrays.

const obj = {
   name: "John",
   age: 10,
   address: {
       street: "Street 1",
       postalCode: "7557-40"
   },
   favouriteCountries: ["Portugal", "Spain"],
   nestedObject: { x: { y: { z: {w: "property" } } } }
}

Then we will call the flatten function, passing as first input our object and as second input an object representing options of the flattening procedure. You can check here the signature of the function.

For all the available properties supported by the options object, please check here. In our case, we want to use the delimiter property, which allows us to set a custom separator.

So, if we want to use, for example, a slash as a separator, we would need to pass the following options object:

{delimiter: "/"}

Putting the whole flatten call together and printing the result to the console, we get the following:

console.log(flatten(obj, {delimiter: "/"}));

Note that the delimiter property is a string, which means we can specify more than a single character.

console.log(flatten(obj, {delimiter: "|separator|"}));

The final code can be seen below.

const flatten = require('flat').flatten;
  
const obj = {
   name: "John",
   age: 10,
   address: {
       street: "Street 1",
       postalCode: "7557-40"
   },
   favouriteCountries: ["Portugal", "Spain"],
   nestedObject: { x: { y: { z: {w: "property" } } } }
}
 
console.log(flatten(obj, {delimiter: "/"}));
console.log("\n\n\n");
console.log(flatten(obj, {delimiter: "|separator|"}));

Testing the code

To test the code, simply run it using a tool of your choice. In my case I’m using Visual Studio Code with the Code Runner extension.

Upon running the code, you should get an output similar to figure 1. As can be seen, in both cases, our custom separator was used instead of the “.” that is used by default in the package.

Output of the program on the Visual Studio Code IDE.
Figure 1 – Output of the program, showing the custom separator being used.

Leave a Reply

%d bloggers like this: