I'm trying to filter items from array by accessing a nested property & checking if it property value contains a certain string

Viewed 35

I'm trying to filter an array of objects by the summary nested property, if it includes the word Save in the summary prop value string. This is the array:

const issues = [{
    id: '1',
    key: 'CLS-1',
    fields: {
      summary: 'Save princess',
      assignee: 'Mario',
    }
  },
  {
    id: '2',
    key: 'CLS-2',
    fields: {
      summary: 'Save Mario',
      assignee: 'Luigi',
    }
  },
  {
    id: '3',
    key: 'CLS-3',
    fields: {
      summary: 'Kidnap princess',
      assignee: 'Bowser',
    }
  },
  {
    id: '4',
    key: 'CLS-3',
    fields: {
      summary: 'Get kidnap!',
      assignee: 'Peach',
    }
  },
]

I have tried this one-liner:

const getItemsBySummary = items.filter(item => item.fields.includes('Save'));

But I get the error item.fields.includes is not a function. I'm guessing because fieldsis anobjectinstead of anarrayso it cannot run the methodincludes()`. However, I tried like so

const getItemsBySummary = items.filter(item => [item.fields].includes('Save'));

But I get an empty array. What am I doing wrong?

2 Answers

well since fields is an object , and you want to filtre according to the proptery summary , you should use this instead :/

const getItemsBySummary = items.filter(item => item.fields.summary.includes('Save'));

You need item.fields.summary to access the required field.

const items = [{
    id: '1',
    key: 'CLS-1',
    fields: {
      summary: 'Save princess',
      assignee: 'Mario',
    }
  },
  {
    id: '2',
    key: 'CLS-2',
    fields: {
      summary: 'Save Mario',
      assignee: 'Luigi',
    }
  },
  {
    id: '3',
    key: 'CLS-3',
    fields: {
      summary: 'Kidnap princess',
      assignee: 'Bowser',
    }
  },
  {
    id: '4',
    key: 'CLS-3',
    fields: {
      summary: 'Get kidnap!',
      assignee: 'Peach',
    }
  },
]
const res = items.filter(item => item.fields.summary.includes('Save'));
console.log(res);

Related