Flatten Nested Objects In JavaScript & Node.js – jsonflat

Category: Javascript | May 9, 2024
Author:kishor82
Views Total:18 views
Official Page:Go to website
Last Update:May 9, 2024
License:MIT

Preview:

Flatten Nested Objects In JavaScript & Node.js – jsonflat

Description:

jsonflat is a simple JavaScript/Node.js library that flattens nested JavaScript objects into a single level. It takes a nested object and converts it into a flat object, where the keys represent the nested structure using a customizable delimiter.

This library can be useful for developers who might need to store or transmit data in a flat format, such as query parameters, form data, or a NoSQL database like MongoDB.

For example, you’re fetching data from an API, and it arrives as a deeply nested object. Accessing specific values within that structure can involve writing complex code with multiple loops and conditions. Jsonflat solves this problem by creating a flat object where each key represents a path to a value in the original structure. This makes data manipulation, analysis, and storage much simpler.

How to use it:

1. Install Jsonflat using NPM:

# NPM
$ npm install @kishor82/jsonflat

2. Import the flat function into your project.

// node.js
const { flat } = require("@kishor82/jsonflat")
// ES Module
import { flat } from '@kishor82/jsonflat';

3. Now, you can flatten any nested object as follows:

const nestedObject = {
  id: 28802695164,
  date: 'December 31, 2016',
  data: {
    totalUsers: 99,
    online: 80,
    onlineStatus: {
      active: 67,
      away: 13,
      busy: 8
    }
  }
}
const flattenedObject = flat(nestedObject);
// Output
{
  "id": 28802695164,
  "date": "December 31, 2016",
  "data.totalUsers": 99,
  "data.online": 80,
  "data.onlineStatus.active": 67,
  "data.onlineStatus.away": 13,
  "data.onlineStatus.busy": 8
}

4. Jsonflat even lets you customize the delimiter used in the flattened keys. For example, using a hyphen:

const flattenedObject = flat(nestedObject, "-");
// Output
{
  "id": 28802695164,
  "date": "December 31, 2016",
  "data-totalUsers": 99,
  "data-online": 80,
  "data-onlineStatus.active": 67,
  "data-onlineStatus.away": 13,
  "data-onlineStatus.busy": 8
}

Changelog:

v0.1.0-beta.1 (05/09/2024)

  • Update

You Might Be Interested In:


Leave a Reply