Retrieve a specific object element in Javascript using its unique id

Presenting this specific item :

      const list = {
        id: 5,
        name: "customer name",
        projects: [
          {
            id:2, 
            title: "My project One",
            studies: []
          },
          {
            id:4,
            title: "My project Two"
          }
        ]
      }

I am interested in accessing a particular project within this object. Although there are only two projects currently, we anticipate there may be more in the future. How can I retrieve a specific project based on its ID? Please advise on how to accomplish this task. Thanks

Answer №1

In the comments, you mentioned that the data comes from an API. Upon receiving the data, you have the option to remap it so that instead of a list of projects, it becomes an object with keys based on the id field, which I presume is unique.

const allProjects = list.projects.reduce(
    (collected, current) => {
      return { ...collected, ...current };
    }, {})

If that doesn't work, you can also utilize Array's filter method to locate the specific project you need:

const idToFind = 4;
const project = list.projects.filter( project => project.id === idToFind );

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

Infinite scroll feature in Select2 fails to load next page when fetching remote data

I am currently working with Select2 4.0.1. I have utilized ajax to dynamically populate search results based on user input. However, I am facing an issue where the initial search displays results from the first page only and subsequent pages do not load. A ...

The pie chart generated by Google may be small in size, but it certainly packs

Below, you will find my page layout created using Bootstrap 4 and Google Charts. The layout consists of three black boxes, with the one on the right displaying a Google pie chart. However, I'm facing an issue where the area allocated for the chart is ...

Changing the slider based on the format of the price and user input value

Is there a specific place where I should use the .toFixed(2) method to ensure fixed formatting for my range slider output? For example, transforming 1.9 to 1.90 or 2 to 2.00. Additionally, is it feasible to have an input field where the user enters a pri ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

What is the process for converting and transferring the date in Google Apps Script to generate a new event in Google Calendar?

To create an event in GAS, follow this link: https://developers.google.com/apps-script/reference/calendar/calendar#createEvent(String,Date,Date,Object) var event = CalendarApp.getDefaultCalendar().createEvent('Apollo 11 Landing', new Date(& ...

Utilize a custom JQuery script on designated grid displays

I am facing a challenge in implementing a JQuery script on specific Gridviews within my page. The issue lies in the fact that the script is currently being applied to all Gridviews on the page, and I need a way to specify which grids it should apply to. T ...

What is the best way to have the sidebar of a webpage slide out over the main body content that is being displayed?

Issue Summary I am experiencing an issue with the positioning of my sidebar, which is initially located 66% offscreen using -translate-x-2/3. The sidebar is meant to be pulled into view onmouseover, however, the main body content remains stuck in place. I ...

Encountering the error `RollupError: Expression expected` during the compilation of an NPM package

Following the setup of my environment to create my initial NPM package for React JS with ROLLUP bundler, I encountered a RollupError: Expression expected error message as displayed below: Error Message > rollup -c --environment NODE_ENV:development dev ...

Best practices for handling pagination and search/filter functionality in a Node and Express-based REST API

I have been experimenting with Node and Express recently. While I have successfully implemented paging and filtering/searching in a memory-based "mini API" that I built from scratch, my current concern revolves around best practices and the proper approach ...

Tips for enabling the `ignoreUndefinedProperties` feature in Node.js

I'm currently in the process of creating a REST api for my Node.js and Express application. However, I keep encountering an error stating that properties are undefined whenever I attempt to send a request. How can I go about enabling 'ignoreundef ...

Error encountered in Chrome while trying to fetch Next.js PWA with the use of next-pwa: Unhandled TypeError

Hello, I was recently working on a Next.js project and attempted to convert it into a PWA using next-pwa. To start off, I created the next.config.js file. const withPWA = require('next- pwa'); module.exports = withPWA({ pwa: { dest: ...

What method is recommended for importing a Maya model into a three.js scene effectively?

After creating a model in Maya, I attempted to import it into WebGL using ColladaLoader in three.js. Unfortunately, the gradient texture did not appear as expected. Although ColladaLoader provided the most precise representation of the model, the three.j ...

Path expression is not valid as it attempts to access an element

When attempting to modify a single element in an array, I encounter the error message Invalid path expression near attempt to access element. Interestingly, this issue only arises when the array is obtained from --rawInput. For instance: # input: [ 1, 0 ...

What is the best way to transmit information using the POST method in JavaScript?

When using javascript, the typical way to redirect a page with a parameter is the following: window.location = "add-new-cos.jsp?id="+id; However, the id value is sent to the next page using the GET method. I am interested in sending it using the POST met ...

Error: Unable to locate module: cannot find './node_modules/@material-ui/core/IconButton'

Encountering an error in the browser: Error: Failed to compile ./src/components/layout/search/Searchbar.js Module not found: Can't resolve './node_modules/@material-ui/core/IconButton' in 'C:\Users\Ja\Desktop\ ...

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

Toggle the visibility of dropdown list items in different ways: Add or Remove, or Show or

Currently, I am working on a project that involves 3 drop down lists for security questions. I have implemented javascript functionality that triggers an alert when a selection is made in any of the drop down boxes. My challenge now is figuring out how t ...

Issue with Initializing MongoDB Database

Attempting to start a MongoDB database server is resulting in an error where the server fails to start. To address this, I have executed the mkdir -p data/db command in the project directory. The command I am running is: mongod --dbpath=data/ --port 27017 ...

Store the values of a column in a newly generated global array dynamically

I need help with storing the values of a column from a text file into a dynamically allocated array that must be globally declared for future use in my program. The text file I am working with contains the following data: 34932\t13854\t13854&bso ...

Unexpected data output detected in Ajax Json response

I'm having trouble parsing the JSON data to HTML and encountering an undefined value. $.ajax({ type: "GET", url: "http://localhost/rest/api/kkb/detail/?key=39E62227E3294114BE8EADF3B6D2F06E&id=4", dataType: 'jsonp', cross ...