Joelgullander
Joelgullander

Reputation: 1684

Array filtering based on properties in object

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

Upvotes: 1

Views: 56

Answers (4)

jamcreencia
jamcreencia

Reputation: 6902

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

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22524

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

Upvotes: 1

prabhatojha
prabhatojha

Reputation: 2085

Try this

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

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191966

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

Upvotes: 3

Related Questions