Skip to content

tkqubo/deep-key-mirror

Repository files navigation

Deep Key Mirror

npm version CI codecov Bundle size TypeScript License: MIT

Alternative to React's keyMirror which further mirrors properties deep inside the object graph.

Installation

npm install deep-key-mirror

Usage

deepKeyMirror(obj)

Returns a new object whose values equal the .-joined property paths in the given object.

Simple example

import deepKeyMirror from 'deep-key-mirror';

deepKeyMirror({ name: null, age: null }); // { name: 'name', age: 'age' }

The package ships both ESM and CommonJS builds. From CommonJS, reach the default export via .default:

const deepKeyMirror = require('deep-key-mirror').default;

String arrays

A string array is mirrored into an object keyed by its elements:

deepKeyMirror(['apple', 'banana', 'grape']);
// { apple: 'apple', banana: 'banana', grape: 'grape' }

Nested example

Child objects and string arrays are mirrored recursively, with the .-joined paths from the root assigned to each value. (An array containing objects keeps the index-path behaviour instead, e.g. items[0].name.)

import deepKeyMirror from 'deep-key-mirror';

const breakfast = {
  bread: null,
  beverage: {
    milk: null,
    coffee: null,
    beer: 'BEER!',
  },
  fruits: ['orange', 'apple'],
};
const mirrored = deepKeyMirror(breakfast);
/*
mirrored === {
  bread: 'bread',
  beverage: {
    milk: 'beverage.milk',
    coffee: 'beverage.coffee',
    beer: 'beverage.beer',
  },
  fruits: {
    orange: 'fruits.orange',
    apple: 'fruits.apple',
  },
}
*/

Literal types

The return type is inferred as literal types when the argument is an inline literal (or annotated as const):

const keys = deepKeyMirror(['apple', 'banana']);
//    ^? { apple: 'apple'; banana: 'banana' }

When you pass a pre-declared variable, its array elements widen to string[], so use an inline literal or as const to retain literal keys.

TypeScript

TypeDoc-generated documentation is available here

About

Alternative to React's keyMirror

Resources

License

Stars

6 stars

Watchers

2 watching

Forks

Packages

 
 
 

Contributors