find()不返回数据,只是未定义

问题描述 投票:0回答:3

我想从这个JSON中找到()s_id:

 {
        "StatusCode": 0,
        "StatusMessage": "OK",
        "StatusDescription": [
             {
                "s_id": "11E8C70C8A5D78888E6EFA163EBBBC1D",
                "s_serial": "PkMGo",
                "active": 0,
              },
             {
                "s_id": "11E8C70FB9D10DB38E6EFA163EBBBC1D",
                "s_serial": "UgooX",
                "active": 0,
                },
              {
                "s_id": "11E8C7179F85836D8E6EFA163EBBBC1D",
                "s_serial": "IiLnM",
                "active": 0,
                }, .....
            {
                "s_id": "11E8C71905123F1A8E6EFA163EBBBC1D",
                "s_serial": "LVpcP",
                "active": 0,
             }
              }]}

我试着在这里找到但是返回undefined。

 sensors: Sensors[]=[];
 hbp: HBP;
 sensor: Sensors;

     this.ss.getAllS().subscribe(
          sensors => {
            this.sensors = sensors 
            let ss = this.sensors.find(x => x.s_id ===  this.hbp.s_id);
            console.log(ss)
            if (ss) {
              this.selectedSensor = ss.s_id
            }
          }
        );

 selectedSensor : string = this.sensors.filter(
    x => x.s_id === this.sensor.s_id[0])
    .map(y => y.s_serial).join('');

我认为这行有问题:

        let ss = this.sensors.find(x => x.s_id ===  this.hbp.s_id);

因为,hbp返回这个json:

active: 0
homebox_id: "11E8C71154CC8C188E6EFA163EBBBC1D"
sensors: Array(2)
0: {s_serial: "s_id", s_id: "11E8C70C8A5D78888E6EFA163EBBBC1D"}
1: {s_serial: "UgooX", s_id: "11E8C70FB9D10DB38E6EFA163EBBBC1D"}

在这一行中可能会发现这个传感器内部

我在html代码中使用的这个selectedSensor

<input formControlName="s_id" type="text" placeholder="Select " [(ngModel)]="selectedSensor" aria-label="Number" matInput
            [matAutocomplete]="auto">

如何返回数据?

你能问我一个想法吗?

angular typescript find
3个回答
0
投票

你的代码对我来说似乎很好,你确定this.ss.getAllS()方法返回一个StatusDescription类型数组吗?我建议在运行时调试sensors变量中的实际内容。


0
投票

可观察的:传感器,最初将为null,并且您无法访问null属性以比较任何内容。

相反,对传感器值进行快速空值检查,然后执行查找操作:

this.ss.getAllS().subscribe(sensors => {
  if (sensors) {
    this.selectedSensor = this.sensors.find(x => x.s_id === this.hbp.s_id)
  }
});

这是一个StackBlitz示例:https://stackblitz.com/edit/select-id-from-observable


0
投票

使用可以使用如下find函数

  let ss =   this.sensors.find((item) => {
      return item.s_id === this.hbp.s_idl
    })


if (ss) {
    this.selectedSensor = ss.s_id         
      }

如果您正在寻找过滤器,地图和联接组合,请确保您在地图内返回item.property

.filter((item) => {
  return item.s_id ===  ss.s_id
}).map(
  (item) => {
    return item.s_serial
  }
).join( )

检查此示例代码

https://stackblitz.com/edit/arrayfind?file=index.js

© www.soinside.com 2019 - 2024. All rights reserved.