1

Well I am stuck here and I would appreciate some directions of methods I can accomplish this with.

I got an array with questions:

  questions: [
    {
      question: 'lala',
      answer: 'papa',
      categories: ['Handla']

    },
    {
      question: 'xxxx',
      answer: 'yyyy',
      categories: ['Reklamation']
    }
  ]

Based on the categories I want to be able to list the questions accordingly when filtering.

So lets say I want to filter on 'Handla' I should be able to loop out all the questions that has the value 'Handla' matched in the categories array.

mapping through the questions array and doing returning them with an if/else statement will work but im not sure this is the optimal way.

Summary: I want to iterate through questions and pick out objects that matches with my desired category query.

My desired output when requesting "Reklamation" should be

const desiredArray = [{
        {
          question: 'xxxx',
          answer: 'yyyy',
          categories: ['Reklamation']
        }
}]
Joelgullander
  • 1,624
  • 2
  • 20
  • 46
  • 1
    Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – Zenoo Jan 17 '18 at 12:37

4 Answers4

3

Use Array#filter and check if the category (Reklamation in the example) is found in the categories array using Array#includes:

const questions = [{"question":"lala","answer":"papa","categories":["Handla"]},{"question":"xxxx","answer":"yyyy","categories":["Reklamation"]}];
  
const result = questions.filter(({ categories }) => categories.includes('Reklamation'));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

Try this

var result = questions.filter((item) => item.categories.find((cat) => cat === 'Reklamation'))
prabhatojha
  • 1,925
  • 17
  • 30
1

You can use array#filter with array.indexOf.

var data = {questions: [{question: 'lala',answer: 'papa',categories: ['Handla']},{question: 'xxxx',answer: 'yyyy',categories: ['Reklamation']}]}, 
    category = 'Reklamation',
    result = data.questions.filter(({categories}) => categories.indexOf(category) > -1);

console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
1

I would create a reusable function that you can call whenever you want to search by category:

const filterByCategory = (questions, category) => { 
 return questions.filter(q => q.categories.includes(category))
}

filterByCategory(questions, 'Reklamation');

filter takes a callback that returns true if you want to keep the element.

Please see the filter and includes docs for more info

jamcreencia
  • 6,474
  • 1
  • 11
  • 7