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

151
Views
Obtenga los padres de un json donde la cadena en javascript

Tengo esto:

 { 'Payment' : { 'Referenced' : 'referenced payment', 'Conciliate' : 'conciliate payment', 'Multiple' : 'multiple payment' } }

pero puede cambiar en todo momento por nodos aleatorios o agregar más, como:

 { 'Payment' : { 'Referenced' : 'referenced payment', 'Conciliate' : 'conciliate payment', 'Multiple' : { 'mult1' : 'example1', 'mult2' : 'example1' }, 'Inventory' : { 'datastorage' : 'dt1' } }

Todos los nodos se pueden asignar aleatoriamente, y necesito buscar por valor, puedo pasar:

 referenced payment

y necesidad:

 Payment/Referenced

o envío:

 example1

Y yo necesito:

 Payment/Multiple/mult1

No sé si existe algo así.

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

0

 // Function const findPath = (obj, query) => { const makeArray = (obj, path = []) => { const pairs = Object.entries(obj); return pairs.map(([key, value]) => typeof value === "object" ? makeArray(value, [...path, key]) : { path: [...path, key], value } ); }; return ( makeArray(obj) .flat(Infinity) .find(({ path, value }) => value === query)?.path.join("/") ?? null ); }; // Usage const path1 = findPath( { Payment: { Referenced: "referenced payment", Conciliate: "conciliate payment", Multiple: { mult1: "example1", mult2: { test: 123, }, }, Inventory: { datastorage: "dt1", }, }, }, 123 ); const path2 = findPath( { Payment: { Referenced: "referenced payment", Conciliate: "conciliate payment", Multiple: { mult1: "example1", }, Inventory: { datastorage: "dt1", }, }, }, "referenced payment" ); console.log("123: " + path1); console.log("referenced payment: " + path2);

Explicación

El primer paso es convertir el objeto en una matriz lineal del árbol de objetos y sus rutas. Esto se hace recursivamente. Luego, la matriz se aplana para iterar con Array.prototype.find , si el valor coincide con la consulta, se devuelve la ruta, si no se encuentra ninguna coincidencia, devuelve null .

Créditos

Gracias a @Bravo por sugerir una matriz de ruta en lugar de una plantilla literal

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!