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

360
Views
Cómo obtener valor seguro del objeto (devolver nulo cuando no existe)

Quiero buscar una clave en un objeto, pero si la clave no existe, debe devolver un valor nulo, ¿es posible en JavaScript?

 const d = { A: () => { return 'A' }, B: () => { return 'B' }, C: () => { return 'C' }, } const key = 'Z' const func = d[key] // HERE console.log(func)

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Puedes usar o: ||

o el encadenamiento opcional más nuevo y el operador coalescente nulo

NOTA: la función de flecha sugerida por Máté Wiszt debe estar entre () o dará un error

 const d = { A: () => { return 'A' }, B: () => { return 'B' }, C: () => { return 'C' }, } let key = 'A' let func = d[key] || null; console.log(func && func()) key = 'Z' func = d[key] || null console.log(func && func()) func = d[key] || function() { return null }; console.log(func && func()) func = d?.[key] ?? (() => null); // arrow has to be wrapped console.log(func()) // undefined key let key1; console.log({key1}) func = d?.[key1] ?? (() => null); // arrow has to be wrapped console.log("Using undefined key1:",func())

about 4 years ago · Juan Pablo Isaza Report

0

Tu puedes hacer:

 const func = d[key] || () => null;

En este caso, puede llamar a func de forma segura.

about 4 years ago · Juan Pablo Isaza Report

0

Será mejor usar hasOwnProperty para verificar si esa propiedad existe en el objeto d o no.

 const d1 = { A: () => { return "A"; }, B: () => { return "B"; }, C: () => { return "C"; }, Z: undefined, }; const d2 = { A: () => { return "A"; }, B: () => { return "B"; }, C: () => { return "C"; }, }; const key = "Z"; function getValue(obj, key) { return obj.hasOwnProperty(key) ? obj[key] : null; } const func1 = getValue(d1, key); console.log(func1); const func2 = d1[key] || null; // Shouldn't use console.log(func2); const func3 = d1[key] ?? null; // Shouldn't use console.log(func3);

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!