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

103
Views
Elimine las claves de nombre innecesarias de la respuesta json

Estoy trabajando con la respuesta de una API que se ve así:

 res: { result: { _text: 'NOK' }, cod: { _text: 'F09' }, items: { car: { _text: 'f16' }, plane: { _text: 'f11' } } }

Es molesto trabajar con esta respuesta, porque tengo que hacer result._text

Quiero transformar la respuesta en algo como esto:

 res: { result: 'NOK', cod: 'F09', items: { car: 'f16', plane: 'f11' } } }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Simplemente puede obtener todos los datos como se mencionó en Cypherjac, pero si realmente desea convertir la respuesta, puede hacer algo como esto.

 const res = { result: { _text: 'NOK' }, cod: { _text: 'F09' }, items: { car: { _text: "f16" }, plane: { _text: "f11" }} } Object.keys(res).forEach((el) => { if (Object.keys(res[el]).length>1){ //or check if el === 'items' Object.keys(res[el]).forEach((item) => { res[el][item] = Object.values(res[el][item])[0] }) } else{ res[el] = Object.values(res[el])[0] } }) console.log(res) console.log(res.result) console.log(res.cod) console.log(res.items.car)
 .as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

¿Tiene control sobre los datos que devuelve la API?

Si no, entonces esta es una forma más explícita de acceder a los valores sin tener que saber los nombres de las claves.

 // Assuming data is the fetched response from the api let data = { result: { _text: 'NOK' }, cod: { _text: 'F09' }, items: { car: { _text: "f16" }, plane: { _text: "f11" } } } // This function gets the values of the object you've provided function getVal(val){return Object.values(val)[0]}; // Object.values returns an array // So we access the first value since the data has only one key '_text' console.log(getVal(data.result)); console.log(getVal(data.cod)); console.log(getVal(data.items.car)); console.log(getVal(data.items.plane));

Esto es principalmente útil si no está seguro del nombre de la clave que se devuelve

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!