object-projector
v1.2.0
Published
`object-projector` is a lightweight utility for projecting the structure of a prototype object onto a source object. It returns a new object that contains only the properties found in both the prototype and source objects, with values taken from the sourc
Downloads
11
Maintainers
Readme
Object Projector
object-projector
is a lightweight utility for projecting the structure of a prototype object onto a source object. It returns a new object that contains only the properties found in both the prototype and source objects, with values taken from the source. This can be particularly useful for API response filtering, data transformation, and schema validation.
Features
- Recursive Projection: Supports deeply nested objects, ensuring all levels of the structure are projected.
- Immutable: Does not mutate the original objects—returns a new object with the projected structure.
- Flexible: Handles any JavaScript object or JSON structure.
- Simple: Easy to integrate into existing projects for shaping objects or filtering data.
Installation
Install the package using npm:
npm install object-projector
Usage
Here’s an example of how to use object-projector
:
import projectObject from 'object-projector';
const src = {
prop11: {
prop21: 21,
prop22: {
prop31: 31,
prop32: 32,
}
},
prop12: 12
};
const proto = {
prop11: {
prop22: {
prop32: null
}
},
prop12: null,
prop: null
};
const result = projectObject(proto, src);
console.log(result);
// Output: { prop1: { nestedProp2: { deeperProp2: 32 } }, prop2: 12, unusedProp: null }
In this example, the resulting object only contains properties present in both the prototype and the source. The values are copied from the source object, and null
is assigned to properties in the prototype that do not exist in the source.
API
projectObject(prototype: object, source: object): object
- prototype: The object defining the structure you want to project.
- source: The object from which values are extracted.
Returns:
A new object where the structure matches the prototype, and the values come from the source.
Use Cases
- API Response Shaping: Simplify and filter API responses by projecting only the required fields from the full object.
- Schema Validation: Enforce a particular structure on incoming data by using a prototype as a schema.
- Data Transformation: Easily project data into the required structure, avoiding unnecessary properties.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Example Project Structure:
object-projector/
├── index.js # Contains the logic for object projection
├── README.md # Instructions and usage examples
├── package.json # NPM metadata
├── LICENSE # License file (MIT)
└── test.js # Local test file to test functionality
Contributing
Feel free to open issues or submit pull requests to improve the package!