I think there’s an elegant way to do this (maybe using destructuring), but I’m stumped so far. I’d like to assign some of the keys and values from one object to another, conditionally based on a boolean.
function bigObject() {
return { /* an object with lots of keys and values, lots */ }
}
function myFunction(aBool) {
// I want smallObject to be either empty or contain a subset of bigObject, based on aBool
// here's where I am stuck
let smallObject = aBool ? { keyA, keyB } = bigObject() : {};
}
JS complains that keyA is a reference error, and I can see how, even if I had this right, I’d just end up creating keyA and keyB variables, not smallObject as I want.
I know I can do this:
let smallObject = {};
if (aBool) {
let bigObject = bigObject();
smallObject.keyA = bigObject.keyA;
smallObject.keyB = bigObject.keyB;
smallObject.keyC = bigObject.keyC;
// 5 of these
}
But that sure is a lot of stuff to write when I think there’s a way I can write just the props names.
>Solution :
It’s not a problem to use temporary destructuring variables. Just use them again to build the target object. If you want it in one expression, you can use an inline function that performs the destructuring in its parameter variables, and then returns the new object:
let smallObject = aBool ? (
({ keyA, keyB }) => ({ keyA, keyB })
) (bigObject()) : {};
const bigObject = () => ({ keyA: 1, keyB: 2, keyC: 3, keyD: 4});
let aBool = true;
let smallObject = aBool ? (
({ keyA, keyB }) => ({ keyA, keyB })
) (bigObject()) : {};
console.log(smallObject);