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']
        }
}]
1

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

var result = questions.filter((item) => item.categories.find((cat) => cat === 'Reklamation'))

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.