Discover optimized ways to search for and sort through deeply embedded objects

In Vue3, I am working with the object $products, which looks like this:

[{ 
   "id": 1, 
   "item": "Product 1", 
   "productcategories": [{ 
      "id": 300, 
      "title": "Category300" 
   },
   { 
      "id": 301, 
      "title": "Category301" 
   }], 
},
{ 
   "id": 2, 
   "item": "Product 2", 
   "productcategories": [{ 
      "id": 200, 
      "title": "Category200" 
   }], 
},
{ 
   "id": 3, 
   "item": "Product 3", 
   "productcategories": [{ 
      "id": 301, 
      "title": "Category301" 
   },
   { 
      "id": 309, 
      "title": "Category309" 
   }], 
}]

It's important to note that each product can belong to multiple product categories.

My objective is to filter this object and retrieve a new object that includes only products with at least one product category id of 301. The resulting object, $filtered_products, should look like this:

[{ 
   "id": 1, 
   "department_id": 2, 
   "item": "Product 1", 
   "productcategories": [{ 
      "id": 300, 
      "title": "Category300" 
   },
   { 
      "id": **301**, 
      "title": "Category301" 
   }], 
},
{ 
   "id": 3, 
   "department_id": 2, 
   "item": "Product 1", 
   "productcategories": [{ 
      "id": **301**, 
      "title": "Category301" 
   },
   { 
      "id": 309, 
      "title": "Category309" 
   }], 
}]

I am looking for recommendations on how to optimize this search process for efficiency.

Answer №1

If you are looking to perform a one-time search of the data, following the method outlined in @moonwave99's response is likely the most efficient approach.

However, if your requirement involves repeated queries on this data with different category IDs, it would be beneficial to invest upfront in creating a lookup object in the form of a map and utilizing that instead:

const productsByCategoryId =
  products
  .flatMap(p => p.productcategories.map(pc => [pc.id, p]))
  .reduce((map, [catId, product]) => {
    const arr = map.get(catId) ?? [];
    const newArr = [...arr, product];
    const deduped = [...new Set(newArr)];
    map.set(catId, deduped);
    return map;
  }, new Map);

console.log(productsByCategoryId.get(301));

const products = [{
    "id": 1,
    "item": "Product 1",
    "productcategories": [{
        "id": 300,
        "title": "Category300"
      },
      {
        "id": 301,
        "title": "Category301"
      }
    ],
  },
  {
    "id": 2,
    "item": "Product 2",
    "productcategories": [{
      "id": 200,
      "title": "Category200"
    }],
  },
  {
    "id": 3,
    "item": "Product 3",
    "productcategories": [{
        "id": 301,
        "title": "Category301"
      },
      {
        "id": 309,
        "title": "Category309"
      }
    ],
  }
];

const productsByCategoryId =
  products
  .flatMap(p => p.productcategories.map(pc => [pc.id, p]))
  .reduce((map, [catId, product]) => {
    const arr = map.get(catId) ?? [];
    const newArr = [...arr, product];
    const deduped = [...new Set(newArr)];
    map.set(catId, deduped);
    return map;
  }, new Map);

console.log(productsByCategoryId.get(301));

Answer №2

Utilizing Array.prototype.some method:

function checkCategoryExistence(category) {
  return products.filter(
    ({ categories }) => 
      categories.some(({ id }) => id === category
    )
  );
}

Check out the results below:

const products = [{
    "id": 1,
    "name": "Product A",
    "categories": [{
        "id": 100,
        "title": "Category100"
      },
      {
        "id": 101,
        "title": "Category101"
      }
    ],
  },
  {
    "id": 2,
    "name": "Product B",
    "categories": [{
      "id": 200,
      "title": "Category200"
    }],
  },
  {
    "id": 3,
    "name": "Product C",
    "categories": [{
        "id": 101,
        "title": "Category101"
      },
      {
        "id": 109,
        "title": "Category109"
      }
    ],
  }
]

function checkCategoryExistence(category) {
  return products.filter(({ categories }) => categories.some(({ id }) => id === category))
}

const filteredProducts = checkCategoryExistence(101);

console.log(filteredProducts);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the process for moving a div to align with another div?

Having just started with HTML and jQuery, I am looking to create three draggable divs stacked one below the other - div1, div2, and so on. I want to drag div1 into the position of div3, changing the order to div3, div1, div2. How can this be achieved? Ple ...

Utilize the power of XMLHttpRequest to fetch and load numerous audio files, seamlessly integrating them for playback through the Web Audio

I am looking to create a web application that loads three different audio files, each one second long, in a specific order, and then merges them into a single Audio Buffer consecutively. To illustrate my goal, here is a sample code snippet: var AudioCo ...

ng-class expressions are constantly evolving and adapting

Within a div, I am utilizing ng-class="{minifyClass: minifyCheck}". In the controller, I monitor changes in two parameters - $window.outerHeight and $('#eventModal > .modal-dialog').height(). If there are any changes, I trigger the minifyChan ...

Generate an array of responses within a child component and then send this array to the parent component using Vue.js 2

Currently, I am in the process of creating a survey using Vue 2. My goal is to construct and emit the answers array to a parent component named Evaluation. You can view the structure of this array here: https://pastebin.com/rLEUh56a Within my project, the ...

Unable to append item to JavaScript Map

Currently, I am attempting to insert an item into a Map (similar to a dictionary) using JavaScript within a React Native environment. import React, { Component } from 'react'; import { AppRegistry, View, Button, } from 'react-native& ...

Design with Internal Elements

Seeking a pattern similar to the code snippet provided below. Interested in learning how to create MyComponent. render(){ <MyComponent> <MyComponent.Something> These children will be displayed </MyComponent.Something> <MyC ...

transfer jquery element using jquery ajax

How can I send a jQuery object to a PHP function using POST? When I stringify the object, I get the following output: [ { "id": "701", "user_id": "2", "playlist": "ukg%20garage", "tracks": "5", "thumbnail": "Coldplay.jpeg", "crea ...

Leveraging a specialized Angular filter as a cellFilter within the columnDefs of ui-grid, set in an Angular constant

In my Angular application called myApp, I have a unique filter named myFilter. Additionally, I am utilizing UI Grid to display data in multiple grids such as myGrid1 and myGrid2. To streamline the process, I have organized column definitions for these grid ...

The Selenium driver's execute_script() function is not functioning as expected

When I attempt to execute a JavaScript using driver.execute_script, nothing happens and the system just moves on to the next line of Python code. Any ideas? I've been web scraping on a webpage, using JavaScript in the Console to extract data. The Jav ...

What is the best way to modify .js source files while using AjaxControlToolkit?

Currently, I am tackling the source code for AjaxControlToolkit in the VS2008 version. There are specific modifications I need to implement in the core javascript files like MicrosoftAjaxWebForms.js, but unfortunately, I am unable to locate the original so ...

How to eliminate spacing between photos in a flexbox layout

[Unique] Find the Solution Image inside div has extra space below the image My design showcases various images of different sizes in multiple rows. See an example here. Despite my efforts, there are noticeable gaps between the rows that I can't seem ...

Angular is throwing an error because it cannot find the definition for

Embarking on a tutorial journey to dive into Angular setup. Facing a persistent error in my code... Error: [$injector:undef] http://errors.angularjs.org/1.6.0/$injector/undef?p0=Bear Listing the order of files within the <head> tag in the html ...

Preventing page re-rendering with redux when a condition is not met

I am currently working on a page that features a question paper with multiple options and a button to navigate to the next question. import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import React, { useEffec ...

What is the process for changing the preserveDrawingBuffer setting in three.js?

Essentially, I am looking to set up a scenario where I can set preserveDrawingBuffer=true, render the scene once, capture the screenshot, and then revert back. However, this presents two challenges: there is no function in the renderer to dispose of all ...

The component is missing either a render function or a template definition in pages/index.vue

component pages/index.vue does not have a defined render function or template I'm puzzled by the meaning of this error message. I followed the stack trace but couldn't pinpoint the exact issue. As I was going through the tutorial on setting up ...

Determine if a parsed JSON has the identical structure of a class in Node.js

I am sending a detailed JSON string to my server, here is a simplified version: { "x": 5; "y": "example" "z": [ { "w": 7 "v": 4 }, { "w": 7 "v": 4 } ] } I am now seeking a way to veri ...

What could be causing the React text input to constantly lose focus with every keystroke?

In my React project using Material-UI library, I have a component called GuestSignup with various input fields. const GuestSignup = (props: GuestSignupProps) => { // Component code goes here } The component receives input props defined by an ...

Create a default function within a mongoose field

Is there a way to achieve the following in my code: var categorySchema = new Schema({ id: { unique: true, default: function() { //set the last item inserted id + 1 as the current value. } }, name: String }); Can this be done? ...

When executing store.sync() in ExtJS, all fields are passed

In the latest version of ExtJS (6.5.0), I have set up a Store and an editable grid panel: Ext.define('StateStore',{ extend: 'Ext.data.Store', alias: 'store.stateStore', storeId : 'StateStore', field ...

JavaScript error in the Electron browser is causing a glitch

I am a beginner in the world of Node.js, JavaScript, and Electron. My goal is to create a basic application that can open a local HTML file in a browser window. The local file contains some complex embedded JavaScript (TiddlyWiki). Below is a snippet of sa ...