M
M
mr jeery2018-02-13 05:40:01
JavaScript
mr jeery, 2018-02-13 05:40:01

How to apply filter to nested array?

hello i have an array

const cards = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: [tag: 'nature', id: f1fz2]},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: [tag: 'nature', id: 2fs]},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: [tag: 'nature', id: f11fdfz2]}
   ]

I want to search on the name field and on the values ​​of the tag field inside tags
There are no questions with the name field, I do this
const name='Product A'
this.setState({
        cards:  cards.filter(item => item.name.includes(tag))
      })

And how to apply the filter to the tag inside tags and the name field?
I go around the functions map , forEach but the solution does not fit in my head, help!!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-02-13
@jeerjmin

It is possible in the same way as with name - the includes method, arrays have it too:
cards.filter(n => n.tags.includes(tag))

S
Stalker_RED, 2018-02-13
@Stalker_RED

let foo = cards.filter(item =>
  item.tags.includes('winter')
  && // <-- magic is here
  item.name.includes('Product B')
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question