0

Estoy trabajando con Angular 2.

En primer lugar hago mi consulta a una API y recupero la información en JSON.

Con este método:

getinvfechasensores(fecha1,fecha2){

    return this._http.get(this.url+'getinvfechasensores/' +fecha1 + '/' + fecha2)
             .map(res => res.json());

  }

Luego hago la suscripción a este método con mi 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);
      }

la variable invernadero es mi objeto y lo que hago es asignar la respuesta del JSON a ese objeto:

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
  ){}

}

la estructura de mi JSON es esta:

[
    {
        "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
    }
]

Mi pregunta es la siguiente:

Como puedo recorrer mi objeto de invernadero y buscar en el campo attrName el nombre sensor1 y agruparlo en un string nuevo llamado sensor1 y buscar sensor2 y agruparlo en un string2?

Pero a su vez todo lo que tenga attrName = sensor1 tiene que estar en el String1, todo lo que attrName = sensor2 guardarlo en el String2

Estoy recorriendo el objeto de esta forma, no se si es la mas correcta.

for (let i = this.invernadero.length - 1; i >= 0; i--) {
              console.log('LO QUE CONTIENE EL FOR' + i); // "4", "5", "6"
            }

Un saludo y gracias.

1
  • Qué quieres decir con "agruparlo en un string"? el 10 oct. 2017 a las 15:08

1 respuesta 1

0

Tienes una clase Invernadero, pero realmente no la usas como tal porque no usas su constructor. Cuando la respuesta la pasas de JSON a un objeto Javascript estás creando objetos con los mismos atributos, pero no son realmente de clase Invernadero. Lo que puedes hacer es declarar Invernadero como una interfaz.

Si quieres quedarte sólo con attrValue en el caso de que exista un elemento con attrName=="sensor1" puedes hacer algo como lo siguiente:

var invernaderos=[
    {
        "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
    }
]

if (invernaderos.some(inv => inv.attrName=='sensor1')) {
  let valores= invernaderos.map(inv => inv.attrValue);
  console.log(valores);
}

2
  • Buenas, antes de nada gracias por la respuesta. tengo esto en mi código public invernadero : Invernadero[]; para poder utilizar el clase Invernadero, supongo que al verla en minúscula pensarías eso, fallo mio no comentarlo. Tienes razon, tengo un array con los objetos dentro, entonces me gustaría buscar dentro de cada objeto y si su nombre "attrName " es sensor 1 crear un nuevo array solo con los valores "attrValue" del sensor 1, sensor 2, humedad etc. Tendría que quedar algo así: esta es la variable d0: 22,26,53,66,23,26,54,23,2
    – Manolait
    el 10 oct. 2017 a las 15:26
  • Ahora mismo estoy probando con esto, pero no se si voy por buen camino. for (let i = this.invernadero.length - 1; i >= 0; i--) { //console.log('LO QUE CONTIENE EL FOR' + this.invernadero[i].attrName); // "4", "5", "6" if (this.invernadero[i].attrName == 'sensor1') { //console.log('informacion del if' + this.invernadero[i].attrName); var stringnuevo = []; stringnuevo.push(this.invernadero[i].attrValue); } console.log('variable stringnuevo' + stringnuevo); }
    – Manolait
    el 10 oct. 2017 a las 15:29

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.