Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
Syntax for bracket-notation-property-accessors to conditionally access the entire object rather than a given property

Suppose I have the following:

const myFunction = ({ returnProp = null }) => ({
    propA: 'val1',
    propB: 'val2',
    propC: 'val3'
})[returnProp || {}]
//               ^^
//               not sure what to put here

If returnProp is null, how can I return the whole object?

If I specify returnProp, I would like it returned:

const propA = myFunction({ returnProp: 'propA' }) // 'val1'

If I do not specify it, I'd like the whole object:

const obj = myFunction({})
/*
    {
        propA: 'val1',
        propB: 'val2',
        propC: 'val3'
    }
*/
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can achieve it using nullish coalescing operator.

const myFunction = ({ returnProp = null }) => {
  const obj = {
    propA: "val1",
    propB: "val2",
    propC: "val3",
  };
  return obj[returnProp] ?? obj;
};

console.log(myFunction({ returnProp: "propA" }));
console.log(myFunction({ returnProp: null }));
console.log(myFunction({ returnProp: undefined }));
console.log(myFunction({}));

about 4 years ago · Juan Pablo Isaza Report

0

Could maybe use a getter invoked with an empty string:

const myFunction = ({ returnProp = '' }) => ({
    propA: 'val1',
    propB: 'val2',
    propC: 'val3',
    get ['']() {delete this['']; return this}
})[returnProp]


console.log(myFunction({ returnProp: "propA" }));
console.log(myFunction({}));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!