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

135
Views
Averiguar el número de ocurrencia de una clave en un objeto JS anidado

Tengo un objeto anidado como

 { name: "John", parent:{ parent:{ parent:{ } } } }

Ahora quiero obtener el nivel del objeto principal principal o, básicamente, cuántas veces se ha anidado un objeto principal. En este caso, debería obtener una salida de 3 .

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

0

También podrías hacerlo recursivamente así:

 const obj = { name: "John", parent:{ parent:{ parent:{ parent:{ parent:{ parent:{ } } } } } } } function findk(o,k,l=0){ if (o[k]) l=findk(o[k],k,++l) return l } console.log(findk(obj,"parent"))

about 4 years ago · Juan Pablo Isaza Report

0

Puede adoptar un enfoque recursivo e iterativo al verificar el valor entregado, si es una matriz, luego verificar la clave deseada e iterar todos los valores de la matriz o devolver cero.

 const getCount = (object, key) => object && typeof object === 'object' ? (key in object) + Object .values(object) .reduce((s, o) => s + getCount(o, key), 0) : 0; console.log(getCount({ name: "John", parent: { parent: { parent: {} } } }, 'parent'));

about 4 years ago · Juan Pablo Isaza Report

0

 let obj = { // treat it like a tree name: "John", parent: { parent: { parent: {} } } } const findDepth = (root, key) => { let depth = 0; let loop = (obj) => { if (obj && obj[key]) { loop(obj[key]); depth++; } } loop(root); return depth; } const result = findDepth(obj, 'parent') console.log(result);

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!