I am working with Angular 2.
First, I make my query to an API and retrieve the information in JSON.
With this method:
getinvfechasensores(fecha1,fecha2){
return this._http.get(this.url+'getinvfechasensores/' +fecha1 + '/' + fecha2)
.map(res => res.json());
}
Then I make the subscription to this method with my component
mostrarnombre(){
this._invService.getinvfechasensores(this.fecha1,this.fecha2).subscribe(
response => {
if (!response) {
console.log('error al cargar datos');
} else {
this.invernadero = response;
console.log(this.invernadero);
var f0=this.invernadero.map(item => item.recvTime);
}
the greenhouse variable is my object and what I do is assign the JSON response to that object:
export class Invernadero{
constructor(
public recvTimeTs: string,
public recvTime: string,
public fiwareServicePath: string,
public entityId: string,
public entityType: string,
public attrName: string,
public attrType: string,
public attrValue: string,
public attrMd: string,
public invjuancol: number
){}
}
the structure of my JSON is this:
[
{
"attrMd": null,
"attrName": "sensor1",
"attrType": "Integer",
"attrValue": "22",
"entityId": "palmerillas",
"entityType": "invernadero",
"fiwareServicePath": "ualiof",
"invjuancol": 141,
"recvTime": "2017-09-28T18:09:31.000Z",
"recvTimeTs": null
},
{
"attrMd": null,
"attrName": "sensor2",
"attrType": "Integer",
"attrValue": "26",
"entityId": "palmerillas",
"entityType": "invernadero",
"fiwareServicePath": "ualiof",
"invjuancol": 142,
"recvTime": "2017-09-28T18:09:39.000Z",
"recvTimeTs": null
},
{
"attrMd": null,
"attrName": "humedad",
"attrType": "Integer",
"attrValue": "53",
"entityId": "palmerillas",
"entityType": "invernadero",
"fiwareServicePath": "ualiof",
"invjuancol": 143,
"recvTime": "2017-09-28T18:09:41.000Z",
"recvTimeTs": null
}
]
My question is this:
How can I loop through my greenhouse object and look up the field for attrName
the name sensor1 and bundle it into a new string named sensor1 and look up sensor2 and bundle it into a string2?
But in turn everything that has attrName
= sensor1 has to be in the String1, everything that has attrName
= sensor2 store it in the String2
I am traversing the object in this way, I don't know if it is the most correct.
for (let i = this.invernadero.length - 1; i >= 0; i--) {
console.log('LO QUE CONTIENE EL FOR' + i); // "4", "5", "6"
}
Greetings and thank you.
You have a Greenhouse class, but you don't really use it as such because you don't use its constructor. When you pass the response from JSON to a Javascript object, you are creating objects with the same attributes, but they are not really Greenhouse class. What you can do is declare Greenhouse as an interface.
If you want to keep only with
attrValue
in case there is an element withattrName=="sensor1"
you can do something like the following: