select-properties
v1.1.0
Published
Specify which properties to include or exclude in an object or an array of objects
Downloads
6
Maintainers
Readme
node-select-properties
Specify which properties to include or exclude in an object or an array of objects
Introduction
I made this module to help me use cachegoose. I wanted to be able to cache all properties from queries, but only select specific fields. This is because I have two applications using the same mongodb and redis database, but they don't need the same data.
This module works the same way as mongoose's select function, only difference is that you give it the result, and then give it the fields you want selected.
This is the reason to why I've made this module, but you can use it to solve your own problems!
It can be used
Examples
const selectProperties = require('select-properties');
const target = { foo: '', bar: '' };
// Object to select the fields of
const select = { foo: 0 };
// Exclude the foo property
const result = selectProperties(target, select);
// The result will be { bar: '' }
Select nested properties using dot notation.
const target = {
some: {
nested: {
value: ''
},
other: {
nested: {
value: ''
}
}
}
};
const select = '-some.nested';
const result = selectProperties(target, select);
// The result will be { some: { other: { nested: { value: '' } } } }
NOTE
Both nested paths, and properties, that match the selected field will be targeted.
See example below.
const target = {
some: {
nested: {
value: ''
},
other: {
nested: {
value: ''
}
}
},
'some.nested': {
value: ''
}
};
const select = '-some.nested';
const result = selectProperties(target, select);
// The result will be { some: { other: { nested: { value: '' } } } }
Select the properties of multiple objects.
const target = [{ foo: '', bar: '' }, { foo: '', bar: '' }];
// Array of objects to select the fields of
const select = { foo: 0 };
const result = selectProperties(target, select);
// The result will be [{ bar: '' }, { bar: '' }]
Select using a string.
const select = '-foo';
// Exclude foo
Select specific properties.
const target = [{ foo: '', bar: '' }, { foo: '', bar: '' }];
// Array of objects to select the fields of
const select = { foo: 1 };
const result = selectProperties(target, select);
// The result will be [{ foo: '' }, { foo: '' }]