I have a function:
const mergedPartOfStateWithCurrentSearchValues = (object, valuesToOmit) => {
const {...valuesToOmit, ...rest } = object;
return rest;
};
The first argument is an object. The second argument is an array of string values to omit from the object. I'm trying to return the rest. So this actually doesn't work like that. I've tried to use lodash as well:
const mergedPartOfStateWithCurrentSearchValues = (object, valuesToOmit) => {
const filteredObject = pickBy(object, function (value, key) {
return !valuesToOmit.includes(key)
})
return filteredObject;
};
And it doesn't work as well. I'm running out of ideas. How can I do what I want to and keeping the generic nature of this function?
You could take the entries of your object using Object.entries() and then filter out the entries which keys appear in your valuesToOmit array by using the .includes() and .filter() methods. Then, you can use Object.fromEntries() to build an object from these filtered entries:
const object = {a: 1, b: 2, c: 3};
const valuesToOmit = ['a', 'c']
const mergedPartOfStateWithCurrentSearchValues = (object, valuesToOmit) => {
return Object.fromEntries(
Object.entries(object).filter(([k]) => !valuesToOmit.includes(k))
);
}
const res = mergedPartOfStateWithCurrentSearchValues(object, valuesToOmit);
console.log(res);
If you can't support Object.fromEntries(), you could map the entries returned by Object.entries() to objects, and then merge them into a larger object using Object.assign():
const object = {a: 1, b: 2, c: 3};
const valuesToOmit = ['a', 'c']
const mergedPartOfStateWithCurrentSearchValues = (object, valuesToOmit) => {
return Object.assign(
...Object.entries(object).filter(([k]) => !valuesToOmit.includes(k)).map(([k, v]) => ({[k]: v}))
);
}
const res = mergedPartOfStateWithCurrentSearchValues(object, valuesToOmit);
console.log(res);
Note: You can improve the efficiency of the above method by making valuesToOmit an ES6 Set, and then using the .has() method rather than the .includes() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With