I can have different version of an object:
myObject1 = {
color: 'red',
size : 'big',
name : 'Beautiful red',
count: 2
};
myObject2 = {
color: 'blue',
name : 'Awesome blue',
count : null
};
I need a helper to keep only value i want and which exist :
function myHelper() {
?????
}
myHelper(myObject1, ['color','size','count']) // => { color: 'red', size : 'big', count:2}
myHelper(myObject2, ['color','size','count']) // => { color: 'blue'}
Anyone already created it ?
Convert the object to entries and filter by:
key
) exists in the desired key list (props
)val
) is not null
.const myObject1 = {
color: 'red',
size : 'big',
name : 'Beautiful red',
count: 2
};
const myObject2 = {
color: 'blue',
name : 'Awesome blue',
count : null
};
function myHelper(obj, props) {
return Object.fromEntries(Object.entries(obj)
.filter(([key, val]) => props.includes(key) && val != null));
}
console.log(myHelper(myObject1, ['color','size','count']));
console.log(myHelper(myObject2, ['color','size','count']));
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you want to optimize this, you can change the "array includes" to a "set has" check via:
const myHelper = (obj, props) => (pSet => Object.fromEntries(Object.entries(obj)
.filter(([key, val]) => pSet.has(key) && val != null)))
(new Set(props));