简体   繁体   中英

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

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 . I'm guessing because fields is an object instead of an array so it cannot run the method includes()`. 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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM