按ID的角度过滤数据

时间:2019-04-08 15:43:49

标签: angular typescript

我在一个有角度的项目中有一些数据,我想使用它代替数据库,因为它的数据非常少...大约有5个字段的50个id ...这是数据:

mydata = [

  {
    "id": 3,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text from 3"
  },
  {
    "id": 31,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text from 31"
  },
  {
    "id": 11,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text for 11"
  },
  {
    "id": 21,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text from 21"
  }

]

然后我有一个方法:

getDataText(id) {
    // code to get the text of the data with the selected id
    // do it should get me the data (in this case the text from id 11) 
}

然后在我拥有的component.html文件中:

<button (click)="getDataText(11)">Get Data by Id</button>

我该怎么做?

5 个答案:

答案 0 :(得分:1)

尝试一下:

getDataText(id) {
    let findedData = this.myData.find(i => i.id === id);
    if (typeof findedData === 'undefined') {
       return null;
    }
    return findedData;
} 

请注意,如果没有发现任何条件,结果将为undefined

答案 1 :(得分:0)

这必须工作:

getDataText(id) { const result = this.mydata.filter(x => x.id === id); return result; }

答案 2 :(得分:0)

您的getDataText应该如下所示:

getDataText(id) {
  const data = myData.find(x => x.id === id);
  return data ? data.text : `Cannot find data with id ${id}`;
}

您甚至可以分为两种方法:

getDataById(id) {
  return myData.find(x => x.id === id);
}

getDataText(id) {
  const data = this.getDataById(id);
  return data ? data.text : `Cannot find data with id ${id}`;
}

答案 3 :(得分:0)

getDataText = id => (this.myData.find(i => i.id === id) || {}).text;

这将返回具有给定ID的项目的文本,如果没有给定ID的项目,则返回undefined。

答案 4 :(得分:0)

run()

在这里您可以看到我的example