Locate a deeply nested element within an array of objects using a specific string identifier

Trying to search for an object in an array with a matching value as a string can be achieved with the following code snippet.

Is there an alternative method to optimize this process without utilizing map?

Code:

const arr = [{
    label: 'A',
    options: [{
        label: 'abc',
        value: 'abc'
      },
      {
        label: 'bcd',
        value: 'bcd'
      }
    ]
  },
  {
    label: 'B',
    options: [{
        label: 'cde',
        value: 'cde'
      },
      {
        label: 'def',
        value: 'def'
      }
    ]
  },
  {
    label: 'C',
    options: [{
        label: 'efg',
        value: 'efg'
      },
      {
        label: 'fgh',
        value: 'fgh'
      }
    ]
  }
];
const str = 'cde';
const result = arr.map(obj => obj.options.find(item => item.value === str)).find(val => val !== undefined);
console.log('result', result);

Answer №1

A more efficient approach would be to avoid using both map and find, and instead opt for a simple loop:

let result;
for (const obj of arr) {
    result = obj.options.find(({value}) => value === str);
    if (result) {
        break;
    }
}

For instance, consider the following example:

const arr = [{
    label: 'A',
    options: [{
        label: 'abc',
        value: 'abc'
      },
      {
        label: 'bcd',
        value: 'bcd'
      }
    ]
  },
  {
    label: 'B',
    options: [{
        label: 'cde',
        value: 'cde'
      },
      {
        label: 'def',
        value: 'def'
      }
    ]
  },
  {
    label: 'C',
    options: [{
        label: 'efg',
        value: 'efg'
      },
      {
        label: 'fgh',
        value: 'fgh'
      }
    ]
  }
];
const str = 'cde';
let result;
for (const obj of arr) {
    result = obj.options.find(({value}) => value === str);
    if (result) {
        break;
    }
}
console.log('result', result);

Answer №2

One approach is to employ Array#flatMap using an empty array as the default value.

This method will yield an array containing the desired matching result.

const
    arr = [{ label: 'A', options: [{ label: 'abc', value: 'abc' }, { label: 'bcd', value: 'bcd' }] }, { label: 'B', options: [{ label: 'cde', value: 'cde' }, { label: 'def', value: 'def' } ] }, { label: 'C', options: [{ label: 'efg', value: 'efg' }, { label: 'fgh', value: 'fgh' }] }];
    str = 'cde';
    result = arr.flatMap(obj => obj.options.find(item => item.value === str) || []);

console.log('result', result);

Answer №3

Avoid using find within the map function, which has a time complexity of O(nk);

To optimize the process, retrieve all the options first and then flatten the array to easily locate the desired object.

const arr = [{
label: 'A',
options: [{
label: 'abc',
value: 'abc'
},
{
label: 'bcd',
value: 'bcd'
}
]
},
{
label: 'B',
options: [{
label: 'cde',
value: 'cde'
},
{
label: 'def',
value: 'def'
}
]
},
{
label: 'C',
options: [{
label: 'efg',
value: 'efg'
},
{
label: 'fgh',
value: 'fgh'
}
]
}
];

const str = 'cde';
const result = arr.map(({options}) => options).flat().find(({value}) => value === str)
console.log('result', result);

Answer №4

To meet your specific requirements, you have the option to perform the following:

const arr = [{ label: 'A', options: [{ label: 'abc', value: 'abc' }, { label: 'bcd', value: 'bcd' }] }, { label: 'B', options: [{ label: 'cde', value: 'cde' }, { label: 'def', value: 'def' } ] }, { label: 'C', options: [{ label: 'efg', value: 'efg' }, { label: 'fgh', value: 'fgh' }] }];

const re1 = /"value":"cde"/
const testStr = JSON.stringify(arr);
console.log(""+testStr)

console.log(re1.test(testStr)) // exists

const re2 = /"label":"(\w)+","value":"cde"/g

console.log(testStr.match(re2)) // label

Answer №5

Avoid using the map function by utilizing the find method from the underscore library in this specific situation:

const myObject = _.find(array, (object) => {
    return _.find(object.options, (element) => element.value === searchString);
});

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

The PrimeNG FullCalendar feature seems to be malfunctioning and cannot be located

I've been working on integrating a FullCalendar module into my Angular 7 project. Despite following the steps provided in this link, I haven't had any luck: After executing this command: npm install <a href="/cdn-cgi/l/email-protection" clas ...

Angular's jQuery timepicker allows users to easily select a

Transitioning from jQuery to Angular, we previously utilized the for selecting times due to Firefox not supporting HTML5 input time. While searching for a similar timepicker plugin for Angular to maintain consistency with our past data and styles, I came ...

A guide on navigating to a different component in Vuejs using a link

<div class="enterprise-details" style="margin-top: 20px"> Already signed up? <a href="#"> LOGIN</a></div> <!-- Component for redirection --> <b-button v-if="!registeredUser" class="button-self" v-b-modal.modal-x>Lo ...

Tips for uploading an input file using ajax method instead of a form

I have a dynamic table that sends all input text to my database using ajax. Here is the code I have implemented so far: <script language="javascript" type="text/javascript"> var i = 2; // This variable always points to the last row function test( ...

Avoiding memory leaks in Reactjs when canceling a subscription in an async promise

My React component features an async request that dispatches an action to the Redux store from within the useEffect hook: const fetchData = async () => { setIsLoading(true); try { await dispatch(dataActions.fetchData(use ...

Issues with the play() method in Javascript across Firefox, Safari, and IE 11 are causing functionality problems

I developed a basic video and audio player that smoothly fades out an introductory image and starts or stops playing an mp4 file upon click. Everything functions properly in Chrome, but unfortunately does not work in other major browsers. Despite checking ...

The behavior of JavaScript replace varies between Chrome and IE

This JavaScript code successfully replaces a string in Chrome: myUrl = someUrl.replace('%2C%7B%22itn%22%3A%5B%22%20guidelines%20%22%5D%7D', ''); However, when tested in Internet Explorer, it does not replace the string as expected. T ...

Execute asynchronous JavaScript request

When a user types something into the input id=2, an ajax function triggers. Here is the HTML: <input id="2" type="text" onkeyup="posttitulo(this.value)" /> And here is the SCRIPT: function posttitulo(value){ $.post("getdata/posttitulo.php",{p ...

Issue (@websanova/vue-auth): http plugin has not been properly configured in drivers/http/axios.js

I've been working on integrating vue-auth into my laravel-vue application, but I'm encountering some console errors: Error (@websanova/vue-auth): drivers/http/axios.js: http plugin has not been set. Uncaught TypeError: this.plugins.http is u ...

Combining Objects within an Array in JavaScript When Certain Conditions Are Satisfied

In my scenario, I am seeking assistance with merging the values of objects in an array if the id matches the warehouse_item_id. Specifically, there are two objects that need to be merged: id 191 and id 52 because id 52 has a warehouse_item_id of 191. Ple ...

Next.js Content Switching: A Step-by-Step Guide

On my app, I have a main dashboard featuring a sidebar navigation and content container. However, being new to next.js and its routing system, I'm unsure how to update the content when a user navigates using the sidebar. Do I need to create separate p ...

Vue.js v-for dynamically creates HTML blocks that capture the state of collapse with two-way data binding

I am currently working on capturing the click action state within an HTML v-for generated block for a collapsible function. I have set up a data table and it seems that the state is being captured correctly. However, I am facing an issue where the displa ...

Can Angular JS handle Object Logging?

Exploring the possibility of using Angular JS with MVC 5.0, I am looking for a way to log the complete class Object into a database whenever an Insert/Edit/Delete operation is performed. Is there a library available in Angular JS that can help serialize ...

What is the process for removing a specific row from a datatable?

I have implemented a data-table using Vue and Vuetify. When I click on the delete icon in a specific row, a snackbar pops up with two buttons - yes and no. If I click on the yes button, I want to delete that specific row. How can I achieve this functionali ...

Basic Search tool, displaying a <div>

Hey there, I've been searching for a solution for a while now and haven't found one yet. So here's my question: I created a simple website to display random recipes for those times when you're not sure what to make for dinner. I also w ...

Is there a more efficient method for replacing all attributes on cloned elements?

While this code does the job, I can't help but feel like it's a bit outdated. I'm not very experienced with JS/JQuery and only use them when necessary. My approach involves cloning an element and then replacing all of its attributes with on ...

Display a div based on user selection using Ajax and Laravel

There are two div elements on the index page containing a datatable. By default, these two divs should be hidden. When an option is selected from the dropdown menu, the corresponding div should be displayed. The webpage is designed for searching within a ...

What are some effective solutions for resolving design problems in Isotope?

When I append the ajax coding, the data is coming fine. However, when I append this style="position: absolute; left: 468px; top: 0px;" css to the new appended data, it is not working. How can I achieve this? Below is my ajax code. Please provide suggestion ...

What is the method to retrieve data in Vue when utilizing arrow functions?

When utilizing Vue and arrow functions in methods, we encounter the issue that arrow functions do not have a this keyword. The question then arises of how to access data properties such as list or object. export default { data() { return { list ...

What is the process of uploading a file from a Vue.js app to the local public disk in Laravel?

Hello there, I am looking to upload a file from a Vue.js app to the local public directory of Laravel and only store the unique name in MySQL upon form submission. However, I am unsure how to achieve this using JavaScript. // Template Tag <input type= ...