Retrieve a specific value nested within an array that is contained within an array of objects

//Organizing data
const resources = {
  categories: [
    { name: 'Category X', items: [ { id: 0, title: 'Item X'} ] },
    { name: 'Category Y', items: [ { id: 1, title: 'Item Y'} ] },
  ]
};

//Fetching the item    
const itemId = 1;
const category = resources.categories.find(c => c.items.find(i => i.id === itemId));
const item = category.items.find(i => i.id === itemId);

//Displaying the result    
console.log(item);

While the above implementation is functional, I believe there could be a more efficient approach to retrieving an object from an array, especially when needing to repeat the code multiple times...

Answer №1

One way to achieve this is by using the Array.forEach method along with Array.find

//Lets create a structure
const data = {
  categories: [
    { name: 'Category A', items: [ { id: 0, label: 'item A' } ] },
    { name: 'Category B', items: [ { id: 1, label: 'item B' } ] },
  ]
};

//Search for a specific item  
const id = 1;
let item;
data.categories.forEach(category => {
  item = category.items.find(i => i.id === id);
});

//Display the result   
console.log(item);

Answer №2

To search for a specific value within an object, you can implement a recursive function that traverses through the object's properties.

function searchForObject(obj, prop, val) {
    var result;
    
    if (obj[prop] === val) {
        return obj;
    }
    if (obj && typeof obj === 'object') {
        Object.values(obj).some(o => result = searchForObject(o, prop, val));
    }
    return result;
}

var data = { items: [{ name: 'Item A', value: 100 }, { name: 'Item B', value: 200 }] };

console.log(searchForObject(data, 'value', 100));
console.log(searchForObject(data, 'name', 'Item B'));

Answer №3

There seems to be an error in your code at

const sectionDef = definitions.find
, it should be corrected to
const sectionDef = definitions.sections.find
since find method only works with arrays. Your current approach is good and will help you achieve the desired outcome.

const definitions = {
  sections: [
    { title: 'Section A', actions: [ { id: 0, name: 'action A' } ] },
    { title: 'Section B', actions: [ { id: 1, name: 'action B' } ] },
  ]
}

const id = 1;
const sectionDef = definitions.sections.find(s => s.actions.find(a => a.id === id));
const actionDef = sectionDef.actions.find(a => a.id === id);

console.log(sectionDef);
console.log(actionDef);

Answer №4

const sections = {
  parts: [
    { area: 'Part X', tasks: [ { id: 0, name: 'task X' } ] },
    { area: 'Part Y', tasks: [ { id: 1, name: 'task Y' } ] },
  ]
}
const id = 1;
var result2;
var data = sections.parts;
var result = data.filter(function(obj) {
    var data2 = obj.tasks;
    result2 = data2.filter(function(obj) {
        return obj.id == id;
    });
});
console.log(result2);

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

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

Working with JSON data retrieved from a PHP and MySQL backend in an AngularJS application

Having difficulty handling the JSON response from PHP. I am using AngularJs to display the received JSON data. As a newcomer to Angular, I attempted a basic exercise and would appreciate some assistance. Thank you in advance. index.html <!DOCTYPE HTML ...

Ways to automatically change a URL into a clickable link upon pasting

When attempting to paste a URL into the text box such as https://stackoverflow.com/, it does not automatically convert to a hyperlink. I previously tried using regular expressions in this related question. The function I implemented worked correctly, howe ...

Connecting elements within an object using VueJs

Within my object "info_login," I gather account information: async created() { try { const res = await axios.get(inscriptionURL); this.comptes = res.data; this.comptes.forEach(element => { const data = {'pseudo': ...

Defining global 'require' scripts in Node.js

Seeking a solution to a slightly unusual problem. I hope that using simple examples will clarify my query, as explaining my complex usage can be challenging. I am incorporating my custom modules into the routes.coffee file for an Express server. My goal i ...

Store the selected checkbox values in an array when submitting in Ionic

One issue I am facing is that the checked checkboxes are returning true instead of the value of input (type="checkbox"). Array displaying responded checked or unchecked items I am unable to store this data in an array as needed. Additionally, I cannot sp ...

Error: The function $(...).draggable is not recognized" and "Error: The object $.browser is not defined

I encountered an error stating, TypeError: $(...).draggable is not a function. To resolve this issue, I added jQuery as follows: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> < ...

What is causing the bullets for the unordered list to appear before the items are inserted into the list?

Can you explain why the bullets are showing up before the list items are added? <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>To Do List</title> </head> <body> ...

Ways to retrieve information from a different website's URL?

Having a bit of an issue here. I'm currently browsing through some reports on webpage #1 () and I have a specific requirement to extract the object named "data" from webpage #2 (). However, the code I've used seems to fetch the entire webpage ins ...

Utilizing jQuery to dynamically add classes

I am looking to dynamically add a date picker to input fields using jquery. It seems to be working fine for the first text field, but as soon as I add additional fields, it stops working. Any suggestions on how I can fix this? Thank you in advance. <ta ...

What is the best way to implement validation for a textfield to prevent submission if a negative value is entered?

I am working with a text field of type number and I have successfully set a minimum value of 0 to ensure that negative values are not accepted. However, I have encountered an issue where I am unable to delete the 0 once it is entered. Is there a way to fix ...

Troubleshooting a misformatted JSON string that lacks proper double quotes in Java Script

{ DataError: { user_id: [ [Object] ] } } I want to transform this string into JSON structure like below: { "DataError": { "user_id": [ [Object] ] } } Is there a potential method to achieve this outcome from incorrectly formatted JSON string? ...

Exploring the capabilities of Angular and UIGrid for fetching table information

I have been utilizing Angular along with uigrid, which is an excellent library for displaying data in a tabular format. Everything looks good when displaying the table. However, when I update an item and click on a Save button that triggers a rest service ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

Display data from a PHP array in a JavaScript alert box

Within my Wordpress registration form, I am attempting to display the $error array in an alert message. I have experimented with using console.log(), but it does not show any output. Even when using JSON.stringify(), the alert only displays the word: true ...

Storing the usernames of users through local storage is essential for data preservation

My instructor mentioned a unique way to store user names using "localstorage" and arrays in JavaScript. This method ensures that the names are saved even if the page is reloaded. Here is the code snippet for achieving this functionality: html: <!doctyp ...

What is the best way to dynamically set the 'selected' attribute in HTML dropdown options using AngularJS data?

I'm currently in the process of developing an angularJS application. Below is a snippet of my PHP code: <label class="item item-input item-select"> <div class="input-label">Do you possess the right to work in the UK?</div> & ...

How can a JavaScript function be imported into a React component from a location outside the src folder?

I have a utility function in my JavaScript utils.js file within the Django static files. I am looking to make this file accessible for use with React as well. I would like to import this file along with its functions into a React component. Here is an ex ...

How can I easily swap between the front and back cameras while using an app?

Trying to create a web-ar experience that allows users to switch between front and back cameras while utilizing SLAM/6dof with the back camera has been a challenging endeavor. While attempting this in PlayCanvas, I faced difficulties getting the front came ...

Utilizing the Bootstrap 5 Alpha validation script within a React environment

I've been working on implementing Bootstrap 5 alpha's validation in my React app. https://i.sstatic.net/tbqLr.png The form should not submit if left blank, and it should display a check or an error mark at the bottom accordingly. So far, I&apo ...