Alternative to React's keyMirror which further mirrors properties deep inside the object graph.
npm install deep-key-mirror
deepKeyMirror(obj)Returns a new object whose values equal the .-joined property paths in the given object.
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;
A string array is mirrored into an object keyed by its elements:
deepKeyMirror(['apple', 'banana', 'grape']);
// { apple: 'apple', banana: 'banana', grape: 'grape' }
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',
},
}
*/
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.
TypeDoc-generated documentation is available here