I have found myself needing to copy the structure of an object without any values.
For example:
var foo = {
name: 'Leo',
address: '1234 Road'
}
var bar = someFunction(foo);
// bar now should equal:
// {
// name: undefined,
// address: undefined
// }
I do realize I can loop through the object keys and assign to the result, was just hoping there might be a simpler method.
Note: I chose the answer I did because it is the one I decided to use, but all the answers were excellent.
Using Object.keys()
to get properties of original object first. Secondly you can use for example Array.prototype.reduce()
to create a new object with the expected keys and values.
This can work for you:
const foo = {
name: 'Leo',
address: '1234 Road'
};
const result = Object.keys(foo).reduce((a,c) => {
a[c] = undefined;
return a;
}, {});
console.log(result);
I hope that helps!