user11287150
user11287150

Reputation:

Angular Filter Data by id

I have some data in an angular project which I want to use instead of a database as it's very little data...about 50 id's with 5 fields...here is the data:

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"
  }

]

Then I have a method:

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

Then in the component.html file I have:

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

How can I do this?

Upvotes: 0

Views: 9977

Answers (5)

Pavel
Pavel

Reputation: 111

public result = "Get Data by Id";
public getDataText(id) {
  const reqObj = this.mydata.find(item => item.id === id);
  this.result = reqObj ? reqObj.text : 'nothing found';
}


<button (click)="getDataText(11)">{{result})</button>

Here you can see my example

Upvotes: 0

hamed
hamed

Reputation: 8043

Try this:

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

Note, if nothing found with condition, result will be undefined.

Upvotes: 2

Will Taylor
Will Taylor

Reputation: 1759

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

This will return the text of the item with the given id, or undefined if there is no item with the given id.

Upvotes: 0

Guillaume Nury
Guillaume Nury

Reputation: 393

Your getDataText should looks like:

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

You could even split in two methods:

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}`;
}

Upvotes: 0

Taher
Taher

Reputation: 258

This must work:

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

Upvotes: 0

Related Questions