JSPM

nested-object-map

1.2.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 106
  • Score
    100M100P100Q69816F
  • License MIT

Deep convert a nested Object into a ES6 Map.

Package Exports

  • nested-object-map

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (nested-object-map) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

NestedObjectMap Class

Deep convert a nested Object into a ES6 Map

Build Status Coverage Status Dependencies Status

npm install nested-object-map

Usage

new NestedObjectMap([object])

The NestedObjectMap Class extends Map and behaves the same way with the difference that the passed objects field values will be mapped. If the object is nested (containing more instances of Object) references to those objects will be mapped as well. Sub-objects will be iterated and their fields will be mapped just the same but their field names will be prefixed with its path. Cyclic references and other objects (eg. arrays) will be mapped as reference. Scalar values are mapped as scalar values, setting them on the map will not change the original objects value.

const NestedObjectMap = require('nested-object-map');

const config = new NestedObjectMap({
  api: {
    http: {
      auth: {
        token: 'secret'
      }
    }
  }
});

const authToken = config.get('api.http.auth.token');
const { token } = config.get('api.http.auth');

console.dir(authToken); // "secret"
console.dir(token); // "secret"

NestedObjectMap.mapObject([object])

You can map another objects fields to the Map (similar to a "deep merge"). This is the same method the constructor calls.

config.mapObject({
  api: {
    http: {
      port: 8080
    }
  }
});

console.dir(config.get('api.http.port')); // 3000
console.dir(config.get('api.http.auth.token')); // "secret"

Use case

It can help you to access values contained deep within nested objects more easily and without the need of too many safe guards. It's probably most useful when dealing with nested objects with unreliable structure.

if (object && object.api && object.api.http && object.api.http.auth) {
  const token = object.api.http.auth.token;
}

// VS

const config = new NestedObjectMap(object);
const token = config.get('api.http.auth.token');

There are similar modules for flat objects: