I am working with the response from an API which looks like:
res: {
result: { _text: 'NOK' },
cod: { _text: 'F09' },
items: {
car: { _text: 'f16' },
plane: { _text: 'f11' }
}
}
This response is annoy to work with, because i have to do result._text
I want to transform the response into something like this:
res: {
result: 'NOK',
cod: 'F09',
items: {
car: 'f16',
plane: 'f11' }
}
}
CodePudding user response:
You can simply obtain all the data as Cypherjac mentioned but if you really want to convert the response can do something like this.
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; }
CodePudding user response:
Do you have control over the data being returned by the API?
If not, then this is a more explicit way of accessing the values without having to know the names of keys..
// 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));
This is mostly useful if you are not sure of the name of the key being returned
