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

686
Views
JavaScript: ¿Cómo obtener la clave del objeto principal por valor del objeto secundario?

¿Puede ayudarme a crear una función que pueda encontrar la clave del objeto principal por el valor del objeto secundario?

Esta es la estructura del objeto:

 const mainObject = { FIRST: { key1: 'value1', key2: 'value2', }, SECOND: { key3: 'value3', key4: 'value4', }, };

Intenté usar esta función:

 function getKeyByValue(object, value) { return Object.keys(object).find((key) => object[key] === value); }

pero si ejecuto getKeyByValue(mainObject, 'value4') devuelve indefinido.

¿Puede alguien ayudarme a mejorar la función getKeyByValue para obtener la clave principal (necesito obtener el nombre 'SEGUNDO')?

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

0

Hacerlo recursivamente es una opción.

 let path = []; let parent = ''; function getParent(path, json, value) { for (var key in json) { if (typeof json[key] === 'object') { path.push(key.toString()); getParent(path, json[key], value); path.pop(); } else { if (json[key] == value) { parent = path[0]; } } } } const mainObject = { FIRST: { key1: 'value1', key2: 'value2', }, SECOND: { key3: 'value3', key4: 'value4', }, }; getParent(path, mainObject, 'value4'); console.log(parent);

about 4 years ago · Juan Pablo Isaza Report

0

tu problema es que revisas las claves incorrectas (objetos)

 const mainObject = { FIRST: { key1: 'value1', key2: 'value2', }, SECOND: { key3: 'value3', key4: 'value4', }, }; function getKeyByValue(object, value) { //you can see that the first keys are for the first objects (first and second) this method doesnt give nested keys. console.log(Object.keys(object)); return Object.keys(object).find((key) => Object.keys(object[key]).some((key2) => object[key][key2] === value)); } //you can also do this and check directly the values function getKeyByValue2(object, value) { //you can see that the first keys are for the first objects (first and second) this method doesnt give nested keys. console.log(Object.keys(object)); return Object.keys(object).find((key) => Object.values(object[key]).indexOf(value) > -1); } console.log(getKeyByValue(mainObject, 'value4')); console.log(getKeyByValue2(mainObject, 'value4'));

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!