Essentially what I want
let schema = {
name: null,
lastname: null
}
let values = {
name: "John",
unwanted: "haxor"
}
to end up in:
console.log(sanitized); // {name: "John", lastname: null}
--
Using Object.assign(schema, values)
ends up with the unwanted value.
Is there a simple way?
Edit: I should add, this is to avoid using a library like lodash or underscore, so if the solution is overly complex, they would be preferable solutions.
There is no builtin method which achieves that. However, there is a simple (almost trivial) way to do it:
const sanitized = {};
for (const p in schema)
sanitized[p] = (p in object ? object : schema)[p];
Just retrieve the same key from the other object:
Object.keys(schema).forEach(key => schema[key] = (key in values ? values : schema)[key]);
If you want to create a new object:
var newObj = {};
Object.keys(schema).forEach(key => newObj[key] = (key in values ? values : schema)[key]);
Also, this is compatible with previous version of ES as well (if you do not use arrow function, of course).
The (key in values ? values : schema)[key])
part assures properties that are only in first schema aren't set to undefined
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