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

92
Views
Convierta una matriz en una estructura de objeto anidado usando Javascript

Estoy tratando de convertir una matriz de objetos en una estructura de objetos anidados usando Javascript , pero el resultado no es el esperado. Estoy explicando mi código a continuación.

 let data = [ { "hop_no": 1, "jumphost_id": "jumphost1" }, { "hop_no": 2, "jumphost_id": "jumphost2" }, { "hop_no": 3, "jumphost_id": "another-jumphost" }, { "hop_no": 4, "jumphost_id": "last-jumphost" } ] let result =''; for(let i = 0; i< data.length; i++) { const index = i+1; const obj = data.find(o => o.name === index); if(result === '' && !result['host-id']) { result = { "host-id": obj.jumphost_id, "next-hop":{} } }else{ if(result['next-hop'] === '') { result['next-hop'] = obj.jumphost_id } } }

Aquí se proporciona la matriz de objetos, es ie- data y mi estructura esperada se proporciona a continuación.

Resultado esperado a continuación.

 { "host-id": "jumphost1", "next-hop": { "host-id": "jumphost2", "next-hop": { "host-id": "another-jumphost", "next-hop": { "host-id": "last-jumphost", } } } }

Aquí la condición es cuando "hop_no": 1 el valor jumphost_id respectivo se asignará a host-id y será la primera clave. después de eso, la estructura del objeto anidado se formará en orden ascendente del valor hop_no y el valor jumphost_id respectivo se asignará a la clave next-hop . ¿Alguien puede ayudarme a diseñar esta estructura usando solo Javascript?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puedes hacer esto con una función de reduce :

 let data = [{ "hop_no": 1, "jumphost_id": "jumphost1", ip: "", port: 22, user: "", password: "", "device-type": "linux" }, { "hop_no": 2, "jumphost_id": "jumphost2", ip: "", port: 22, user: "", password: "", "device-type": "linux" }, { "hop_no": 3, "jumphost_id": "another-jumphost", ip: "", port: 22, user: "", password: "", "device-type": "linux" }, { "hop_no": 4, "jumphost_id": "last-jumphost", ip: "", port: 22, user: "", password: "", "device-type": "linux" } ] let result = data.sort((a, b) => b.hop_no - a.hop_no).reduce((prev, curr, i, array) => { let { hop_no, jumphost_id, ...rest } = curr return { 'host-id': jumphost_id, ...rest, ...(i > 0 ? {'next-hop': { ...prev }} : {}), } }, {}) console.log(result)

about 4 years ago · Santiago Trujillo Report

0

Puedes intentar construir el objeto de adentro hacia afuera.

Al igual que:

 let data = [ { "hop_no": 1, "jumphost_id": "jumphost1" }, { "hop_no": 2, "jumphost_id": "jumphost2" }, { "hop_no": 3, "jumphost_id": "another-jumphost" }, { "hop_no": 4, "jumphost_id": "last-jumphost" } ] let result = {}; for (var i = data.length - 1; i >= 0; i--) { let tmp = { 'host-id': data[i]['jumphost_id'], }; if (Object.keys(result).length !== 0) { tmp['next-hop'] = result; } result = tmp; } console.log(result);

about 4 years ago · Santiago Trujillo 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!