skip to Main Content

In the below data array if a user is able to search with Fruits (Category) or Apple (Subcategory).

const data = [
  {
    "category": "Fruits",
    "subCategory": [
      {
        "id": 1,
        "val": "Apple"
      },
      {
        "id": 2,
        "val": "Banana"
      }
    ]
  },
  {
    "category": "Vagitable",
    "subCategory": [
      {
        "id": 1,
        "val": "Tomato"
      },
      {
        "id": 2,
        "val": "Potato"
      }
    ]
  }
]

Output: Search value "Fruits" or "Apple".

const data = [{
"category": "Fruits",
"subCategory": [
{
"id": 1,
"val": "Apple"
}
] }]

2

Answers


  1. You search category and subCategory by find() array manipulation method.

    const data = [
      {
        "category": "Fruits",
        "subCategory": [
          {
            "id": 1,
            "val": "Apple"
          },
          {
            "id": 2,
            "val": "Banana"
          }
        ]
      },
      {
        "category": "Vagitable",
        "subCategory": [
          {
            "id": 1,
            "val": "Tomato"
          },
          {
            "id": 2,
            "val": "Potato"
          }
        ]
      }
    ]
    
    const searchValue = "Tomato";
    
    const output = data.find(items => 
      items.category === searchValue || 
      items.subCategory.some(subItem => subItem.val === searchValue)
    );
    
    console.log(output);
    Login or Signup to reply.
    • you need to use find method to achieve desired solution first we find
    • in the main array and match with category if not find with category
    • then check with subcategory
    const data = [
      {
        "category": "Fruits",
        "subCategory": [
          {
            "id": 1,
            "val": "Apple"
          },
          {
            "id": 2,
            "val": "Banana"
          }
        ]
      },
      {
        "category": "Vagitable",
        "subCategory": [
          {
            "id": 1,
            "val": "Tomato"
          },
          {
            "id": 2,
            "val": "Potato"
          }
        ]
      }
    ];
    let input="Fruits";
    let result = data.find(item => {
        if(item.category == input)
            return item;
        else{
           let ret=[];
           ret.push(item.subCategory.find(item2 => {
               return item2.val == input
            }))
            item.subCategory=ret;
            return item;
        }
    });
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search