Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 .filter within a .filter

So I have data like the following:

[
     {
      "id": 0,
      "title": "happy dayys",
      "owner": {"id": "1", "username": "dillonraphael"},
      "tags": [{"value": "Art", "label": "Art"}],
      "items": []
     },
     {
      "id": 1,
      "title": "happy dayys",
      "owner": {"id": "1", "username": "dillonraphael"},
      "tags": [{"value": "Architecture", "label": "Architecture"}],
      "items": []
     },
]

I'm trying to filter through an array and only return if the tags array contains a value that is == to another string.

This is what I came up with but still seems to be sending back the whole array:

const tagMoodboards = _moodboards.filter(mb => { return mb.tags.filter(t => t.value == name) })
like image 938
Dileet Avatar asked Jun 22 '26 10:06

Dileet


1 Answers

You don't want a filter inside a filter - rather, inside the filter, check if some of the tags objects have the .value property that you want

const _moodboards = [
     {
      "id": 0,
      "title": "happy dayys",
      "owner": {"id": "1", "username": "dillonraphael"},
      "tags": [{"value": "Art", "label": "Art"}],
      "items": []
     },
     {
      "id": 1,
      "title": "happy dayys",
      "owner": {"id": "1", "username": "dillonraphael"},
      "tags": [{"value": "Architecture", "label": "Architecture"}],
      "items": []
     },
];
const name = 'Architecture';
console.log(_moodboards.filter(({ tags }) => (
  tags.some(({ value }) => value === name)
)));
like image 161
CertainPerformance Avatar answered Jun 24 '26 01:06

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!