Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditionally assign from part of an object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading