Home > Mobile >  Filter items based on value in nested array
Filter items based on value in nested array

Time:05-09

How do you filter the results using javascript so any item that includes the tag 'help' are excluded from the results?

Here is the object I get back and what I have so far, but obviously doesn't work:

const data = {
  result: true,
  items: [{
      tags: ['typography', 'inspiration'],
      title: 'Typefaces Inspired by the Bauhaus',
    },
    {
      tags: ['layout', 'ratio', 'help'],
      title: 'Building a combined CSS-aspect-ratio-grid',
    },
  ]
}

const items = data.filter(data => data.tags !== 'help');

console.log(items)

CodePudding user response:

You need to filter the data.items and use !some or !includes

Here is the data without the help in the items using includes

const data = {
  result: true,
  items: [{
      tags: ['typography', 'inspiration'],
      title: 'Typefaces Inspired by the Bauhaus',
    },
    {
      tags: ['layout', 'ratio', 'help'],
      title: 'Building a combined CSS-aspect-ratio-grid',
    },
  ]
}

data.items = data.items.filter(item => !item.tags.includes('help')); 

console.log(data)

CodePudding user response:

data.items.filter(item=> !item.tags.some(tag => tag === 'help'))

some will return true if any tag equals 'help', so use filter to select item when some returns false

  • Related