Tips for optimizing nested object array searches

Is there a widely recognized technique to chain .map or .filter or .find functions in order to achieve this type of search?

Imagine an array of objects nested within another array of objects

customerGroups : 
[
   {
    id: 1,
    customers: [{
        id: 1, // The same customer may be part of multiple groups
        name: 'Jhon'
    }],
   },
   {
    id: 2,
    customers: [{
        id: 2, 
        name: 'Jhon'
    }],
   },
   {
    id: 3,
    customers: [{
        id: 2, 
        name: 'Doe'
    }],
   },
]

In a scenario where you have the customer's id and want to retrieve the customer's name, I aim to extract the customers array and utilize the Array.Find method

const idSearch = 1
const customerName = customers.find(({id})=>id==idSearch).name

I've been experimenting with

const customers = customerGroup.find(({ customer }) =>
    customer.find(({ id }) =>idSearch === id),
  )?.customers
const customerName = customers.find(({id})=>id==idSearch).name

I believe there must be an optimal approach for this, but I am currently too fatigued to determine it.

I've also attempted various strategies using .map to create a new array with all the customers, but haven't achieved satisfactory results yet.

I could potentially fetch that array from my Backend, but since I already have all the customers stored in memory, that would lead to unnecessary strain.

Answer №1

If you're looking to merge multiple customer arrays into one and then search for a specific ID, you can achieve this by using a combination of flatMap and find:

const customerGroups = [{id:1,customers:[{id:1,name:'Jhon'}]},{id:2,customers:[{id:2,name:'Jhon'}]},{id:3,customers:[{id:2,name: 'Doe'}]}];
const idSearch = 1;

const allCustomers = customerGroups.flatMap(({customers}) => customers);
const name = allCustomers.find(({id}) => id === idSearch)?.name;

console.log(name);

Answer №2

This method is effective because once the inside loop locates a match, both the inner and outer loops will stop, resulting in name being assigned as the matching element that caused the loops to end (or undefined if no match was found).

const data = [{id:1,customers:[{id:1,name:'John'}]},{id:2,customers:[{id:2,name:'John'}]},{id:3,customers:[{id:3,name: 'Doe'}]}]
const idToFind = 1

let name
data.find(j=>j.customers.find(i=>i.id===idToFind && ({name}=i)))

console.log(name)

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

Angular: Exploring the possibilities of condition-based click event implementation

In my component, there are two elements: 'order information' and a 'datepicker'. When clicking on the component, it will display the order information. However, I want to prevent the click event from being triggered if the user clicks ...

Incorporating live text into a tag while arranging items by price in both ascending and descending order

I recently added a button to my online shop that allows users to sort products by price, even though I don't fully understand the underlying JavaScript code. I want to enhance this button by updating the text to indicate whether the sorting order is ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

Exploring AngularJS tab navigation and injecting modules into the system

Two separate modules are defined in first.js and second.js respectively: first.js var app = angular.module('first',['ngGrid']); app.controller('firstTest',function($scope)) { ... }); second.js var app = angular.mo ...

When using JavaScript to style.display = "block", the Bootstrap-4 column layout may experience a display break

My div is initially displaying properly in one row at the beginning. However, when the user changes the select option to "b" and then back to "a," the display breaks. The two texts "my left side text" and "my right text" are displayed on two lines, one be ...

I am having trouble with Owl Carousel in my code. Can anyone help me figure out what is causing the issue

I'm having trouble getting my owl carousel to display when I try to run it. I've made sure to link the correct stylesheets and scripts, but nothing is showing up on the page. Even after trying to link the stylesheets from both a local source and ...

JavaScript array as a reliable data storage solution

This is my unique jsp code where I am attempting to push certain data into a JavaScript array. <% int proListSize = proList.size(); ProfileDAO proDAO = null; for(int i = 0, j=1; i < proListSize; i++){ proDAO = ( ...

Synchronizing live data from the database to the front end of a Java-powered web application

I'm currently developing a customer support web application using Java, where I need to display the status of "Customer Representatives (CR)" in the front-end - whether they are available, busy, or away on the phone. When a CR ends a call with a cust ...

Contentful integrated into a NuxtJs website

After successfully creating a blog using Nuxt JS and integrating Contentful into the project, I followed a helpful tutorial from here. This enabled me to retrieve all sections such as title, date, and content of the post efficiently. However, I am current ...

Organizing Parsed JSON Data with JavaScript: Using the _.each function for Sorting

var Scriptures = JSON.parse( fs.readFileSync(scriptures.json, 'utf8') ); _.each(Scriptures, function (s, Scripture) { return Scripture; }); This code extracts and displays the names of each book from a collection of scriptures (e.g., Genesis, ...

instructions for selecting div id within the same "table td" element using jQuery

Here is the code snippet that I am working with: <td> <div id="div<%# Eval("Id") %>" class="Display"><%# Eval("Display") %></div> <div class="Actions"> </div> <div class="Comment"> <span>Comm ...

Collect input from the user for multiple lists and send them to PHP for additional processing

I'm struggling to find the error in this code... I keep getting "undefined index user_list" as the error message. Essentially, I am trying to allow users to input values into a list and then store that entire list in a database. <?php if(isset($_ ...

How can you tell if a specific keyboard key is being pressed along with the CTRL button?

Is there a way to call functions when a specific key is pressed along with the CTRL key (on a Windows system)? While testing for a particular keyCode, I used event.keyCode. I researched the codes assigned to each key and assumed that 17 + 73 would represe ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

What is the best way to integrate a Vue component into the HTML of another Vue component?

Currently, I am dealing with a large HTML string that is being loaded into a div within my Vue component. This HTML string comes from a WYSIWYG editor and was previously handled using v-html, which worked well. However, I now have scenarios where I need t ...

Send an ajax request to upload several images to the server

I am currently facing an issue with my web application that allows users to create posts with a maximum of 15 images. I have implemented AJAX requests to send all the data, including the images, in one request. However, I encountered this error: An error ...

When the JavaScript compiles, React DOM undergoes updates. However, if you try to refresh the browser, an error will occur stating 'Cannot read properties of undefined (reading '1')'

Utilizing the function below: const useApi = url => { const [data, setData] = useState([]); const [isLoaded, setIsLoaded] = useState(false); const [error, setError] = useState(null); useEffect(() => { const fetchData = () =&g ...

Is there a way to compare the attributes of two objects to see if they are similar, except for one attribute?

Looking at the two objects below, my goal is to compare their attributes (name, modifiers, price) for equality without considering one particular attribute (quantity). For instance, in the scenario given, if I were to compare Object A and Object B, they w ...

Troubleshooting the "Request failed with status code 500" error when refreshing a page in a React application

Every time the page is reloaded, an error message pops up saying: Uncaught (in promise) Error: Request failed with status code 500. Here's the code in list.tsx: const [state, setState] = useState([]); const { getRoom } = useRoom(); const fe ...