DBoi
DBoi

Reputation: 687

Typescript/Angular 2 - filter out objects that do not include a specific string property

I'm creating a filter in my angular application that removes all objects that do not contain specific string property within a nested array.

for example... I have an array that looks like this:

JSON:

[
  {
    "id":1,
    "name":"example1",
    "categories": [
      "red",
      "yellow",
      "pink",
      "green"
    ]
  },
  {
    "id":2,
    "name":"example2",
    "categories": [
      "blue",
      "black",
      "purple",
      "green"
    ]
  },
  {
    "id":3,
    "name":"example3",
    "categories": [
      "red",
      "yellow",
      "black",
      "white"
    ]
  }
]

When you click a button the function will only show the objects that contain the specified category.

Something like...

<button (click)="filter('red')">filter by category</button>

filter(category) {
  // only show objects that contain (category) string.
}

Any help would be great cus I just haven't managed to crack it.

Hope this is enough info

Upvotes: 1

Views: 8596

Answers (2)

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

Use filter to filter out your record.

Component

var arr = [
  {
    "id":1,
    "name":"example1",
    "categories": [
      "red",
      "yellow",
      "pink",
      "green"
    ]
  },
  {
    "id":2,
    "name":"example2",
    "categories": [
      "blue",
      "black",
      "purple",
      "green"
    ]
  },
  {
    "id":3,
    "name":"example3",
    "categories": [
      "red",
      "yellow",
      "black",
      "white"
    ]
  }
];


function filterData(colorName) {
    arr.filter((item) => {
      return item.categories.indexOf('white') !== -1;
    });
    console.log(arr);
}

HTML

<button (click)="filterData('red')"></button>

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222552

You can use array.filter and array.includes with !

const data = [
  {
    "id":1,
    "name":"example1",
    "categories": [
      "red",
      "yellow",
      "pink",
      "green"
    ]
  },
  {
    "id":2,
    "name":"example2",
    "categories": [
      "blue",
      "black",
      "purple",
      "green"
    ]
  },
  {
    "id":3,
    "name":"example3",
    "categories": [
      "red",
      "yellow",
      "black",
      "white"
    ]
  }
];


const r = data.filter(d => !d.categories.includes('red'));
console.log(r);

So you need to change your filter function as,

filter(category) {
  const result = data.filter(d => !d.categories.includes(category));
}

Upvotes: 3

Related Questions