pelotador.1
pelotador.1

Reputation: 380

How to find the index of an object within an array based off of the value of an object within said object

I'm working on a project where I need to find the index of the overall object, but I only have the name and value of an object contained within the overall object.

I have an array:

const data = [
{
"category": "Diet", 
"subCategories": [
     {name:'pescatarian', value: false }, 
     {name:'vegan', value: false }, 
     {name:'vegetarian', value: false }
    ]
}, 
{"category": "Daily Exercise in Hours", 
"subCategories": [
      {name:'one', value: false },
      {name:'two', value: false }, 
      {name:'three', value: false }, 
      {name:'four', value: false }
    ]
},
]

and I am able to get item, which for example is equal to: {name:'pescatarian', value: false }, but I need the index of:

{
"category": "Diet", 
"subCategories": [
     {name:'pescatarian', value: false }, 
     {name:'vegan', value: false }, 
     {name:'vegetarian', value: false }
    ]
},

I've tried look at other examples, but I haven't been able to find anything similar and nothing that I have tried so far has worked. Does anyone know how I would do this? I would really appreciate any help or advice. Thank you!

Upvotes: 0

Views: 30

Answers (1)

ryeballar
ryeballar

Reputation: 30098

  • Use Array#findIndex to determine the index of the category you're trying to find.
  • Use Array#some to determine the match within sub categories of each category.

const categories =[{category:"Diet",subCategories:[{name:"pescatarian",value:!1},{name:"vegan",value:!1},{name:"vegetarian",value:!1}]},{category:"Daily Exercise in Hours",subCategories:[{name:"one",value:!1},{name:"two",value:!1},{name:"three",value:!1},{name:"four",value:!1}]},];

const match = {name:'pescatarian', value: false};

function findCategoryIndex(categories, match) {
  return categories
    .findIndex(({ subCategories }) =>
      subCategories.some(({ name, value }) =>
        match.name === name && match.value === value
      )
    )
}

console.log(findCategoryIndex(categories, {
  name:'pescatarian', value: false
}));

console.log(findCategoryIndex(categories, {
  name:'four', value: false
}));

Upvotes: 1

Related Questions