I have a sequence of JSON objects coming from a post request
{
"labels": {
"name": "Toma/Dyrskuvegen5/360.001/Avkasttemperatur"
}
}
In some sequences the labels are empty (in which case should return false), in some, they are not. Also in some sequences the
labels.name
will be some other random key name, for example:
labels.room_number
My task is to identify if there is any key under labels and set two strings, one with the key name, and the other with the key-value example from above:
n = "name"
v = "Toma/Dyrskuvegen5/360.001/Avkasttemperatur"
You can use Object.entries
to do this. It returns an array of a given object's [key, value] pairs
let incoming = {"labels":
{"name":
"Toma/Dyrskuvegen5/360.001/Avkasttemperatur"}};
let incoming2 = {"labels":
{"age":
"22"}};
let incoming3 = {"labels":
{}};
let getThis = (incoming) => {
let entries = Object.entries(incoming.labels);
if(entries.length > 0){
[s,v] = Object.entries(incoming.labels)[0];
console.log(s,v);
}
return false;
};
getThis(incoming3);
getThis(incoming);
getThis(incoming2);