What is the best way to retrieve a specific value from an array of objects based on a condition?

I need some assistance with writing a function. Can you help me out?

Let's say I have an array of objects:

const movieGen = [
    { id: 28, name: "Action" }, { id: 12, name: "Adventure" }, { id: 16, name: "Animation" },
    { id: 35, name: "Comedy" }, { id: 80, name: "Crime" }, { id: 99, name: "Documentary" },
    { id: 18, name: "Drama" }, { id: 10751, name: "Family" }, { id: 14, name: "Fantasy" },
    { id: 36, name: "History" }, { id: 27, name: "Horror" }, { id: 10402, name: "Music" },
    { id: 9648, name: "Mystery" }, { id: 10749, name: "Romance" }, { id: 878, name: "Science Fiction" },
    { id: 10770, name: "TV Movie" }, { id: 53, name: "Thriller" }, { id: 10752, name: "War" },
    { id: 37, name: "Western" }
]

I am in need of a function that will return the name when provided with a matching id. For example-

const genresHandler = (id: number) => { ....//Function to be written here }

If I input 28 as the id, the function should return Action

console.log(genresHandler(28))   output should be: Action
console.log(genresHandler(12))   output should be: Adventure

Can someone assist me in creating this function using either typscript or javascript?

Answer №1

function getGenreName(movieId) {
  const movie = movieGenres.find((movie) => movie.id === movieId);
  return movie ? movie.name : null;
}

One recommended method to search for movies within the movieGenres array is by utilizing the find function. This function takes a callback function that compares and retrieves the first movie entry which has an id matching the one passed to the getGenreName function (movieId). The output of find is then evaluated using a ternary operator, returning the movie's name if it exists, or null if it does not.

Answer №2

Utilize find method to locate the object with the matching id and retrieve the corresponding name value.

The symbol ? represents a relatively recent addition in JavaScript known as optional chaining. It essentially implies that if the object is discovered, return the name; else, provide a default message.

const arr=[{id:28,name:"Action"},{id:12,name:"Adventure"},{id:16,name:"Animation"},{id:35,name:"Comedy"},{id:80,name:"Crime"},{id:99,name:"Documentary"},{id:18,name:"Drama"},{id:10751,name:"Family"},{id:14,name:"Fantasy"},{id:36,name:"History"},{id:27,name:"Horror"},{id:10402,name:"Music"},{id:9648,name:"Mystery"},{id:10749,name:"Romance"},{id:878,name:"Science Fiction"},{id:10770,name:"TV Movie"},{id:53,name:"Thriller"},{id:10752,name:"War"},{id:37,name:"Western"}];

function getGenre(arr, id) {
  return arr.find(movie => {
    return movie.id === id;
  })?.name || 'No genre found';
}

console.log(getGenre(arr, 28));
console.log(getGenre(arr, 12));
console.log(getGenre(arr, 1));

If you desire a more sophisticated approach, you could input an array of ids and obtain all the genres. You could filter out the objects where the ids array contains the movie id (returns an array of movie objects), followed by utilizing map to exclusively fetch the names from those objects.

const arr=[{id:28,name:"Action"},{id:12,name:"Adventure"},{id:16,name:"Animation"},{id:35,name:"Comedy"},{id:80,name:"Crime"},{id:99,name:"Documentary"},{id:18,name:"Drama"},{id:10751,name:"Family"},{id:14,name:"Fantasy"},{id:36,name:"History"},{id:27,name:"Horror"},{id:10402,name:"Music"},{id:9648,name:"Mystery"},{id:10749,name:"Romance"},{id:878,name:"Science Fiction"},{id:10770,name:"TV Movie"},{id:53,name:"Thriller"},{id:10752,name:"War"},{id:37,name:"Western"}];

function getGenre(arr, ids) {
  return arr
    .filter(movie => ids.includes(movie.id))
    .map(movie => movie.name);
}

console.log(getGenre(arr, [28, 12, 9648, 1]));

Answer №3

When using JavaScript, you can create a movieGen array with different genres:

const movieGen = [
{ id: 28, name: "Action" }, { id: 12, name: "Adventure" }, { id: 16, name: "Animation" },
{ id: 35, name: "Comedy" }, { id: 80, name: "Crime" }, { id: 99, name: "Documentary" },
{ id: 18, name: "Drama" }, { id: 10751, name: "Family" }, { id: 14, name: "Fantasy" },
{ id: 36, name: "History" }, { id: 27, name: "Horror" }, { id: 10402, name: "Music" },
{ id: 9648, name: "Mystery" }, { id: 10749, name: "Romance" }, { id: 878, name: "Science Fiction" },
{ id: 10770, name: "TV Movie" }, { id: 53, name: "Thriller" }, { id: 10752, name: "War" },
{ id: 37, name: "Western" }
];

function findGenreById(id) {
  const res = movieGen.filter(element => element.id === id);
  console.log(res[0].name);
}

findGenreById(28); 
 

Answer №4

Locate the target object by utilizing the find() method. Retrieve a specific property:

const movieGenres = [{id:28, name: "Action" }, {id:12,name:"Adventure"}, { id: 16, name: "Animation"}];
const handleGenres = (movieId) =>
movieGenres.find((genre) => genre.id === movieId)?.name ?? ''

console.log(handleGenres(28));
console.log(handleGenres(29));
console.log(handleGenres(12));

To manage scenarios where an item is not present, you can implement optional chaining. The optional chaining feature allows you to access nested properties of an object without needing nested if statements.

Answer №5

function getGenreName(id) {
    const foundGenre = movieGenresArray.find(genre => genre.id === id);
    // if genre is found, return the name, otherwise return null
    return foundGenre ? foundGenre.name : null;
}

Answer №6

const movieGenres = [
    { id: 28, name: "Action" }, { id: 12, name: "Adventure" }, { id: 16, name: "Animation" },
    { id: 35, name: "Comedy" }, { id: 80, name: "Crime" }, { id: 99, name: "Documentary" },
    { id: 18, name: "Drama" }, { id: 10751, name: "Family" }, { id: 14, name: "Fantasy" },
    { id: 36, name: "History" }, { id: 27, name: "Horror" }, { id: 10402, name: "Music" },
    { id: 9648, name: "Mystery" }, { id: 10749, name: "Romance" }, { id: 878, name: "Science Fiction" },
    { id: 10770, name: "TV Movie" }, { id: 53, name: "Thriller" }, { id: 10752, name: "War" },
    { id: 37, name: "Western" }
]

var selectedGenre = movieGenres.filter(item => item.id === parseInt(28)); // pass your value instead of 28
selectedGenre.map(matchedItem => console.log(matchedItem))

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

What steps do I need to take to generate a schematic task?

Angular schematics involves various tasks that can be customized. I am looking to create a new task to execute using the script executor, similar to an example provided by Angular. Currently, I am simply running predefined tasks at the end of the schemati ...

Creating individual components for <select> and <option> elements in ReactJS

I am uncertain about how references function when the select and option tags are used together. When I split them into separate React components, they stop working. How can I resolve this issue? Here is a basic example: <select> {() => ( ...

Ways to determine if content is visible within a div

My website contains a script that brings in content from an ad network and displays it within a div element. Unfortunately, this particular ad network only fills ads 80% of the time, leaving the remaining 20% of the time without any ads to display. This la ...

MongoDB has encountered an error while attempting to combine two disparate conditions

I need to run a MongoDB query using JavaScript. Specifically, I am looking to retrieve documents based on two different criteria. The first condition is as follows: $or: [ { "users.username": user.username }, { buyer: ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

JavaScript issue: TypeError - Information.map is not a function. Learn how to properly use .map method

Currently, I am learning how to use CRUD in React with Express and Node. I have successfully inserted data into the database, but I encountered an error when trying to represent the data using .map. You can see the issue with <Input onClick="{getCR ...

Transforming HTML with JavaScript

I am facing a challenge in my JavaScript application where I receive HTML code from an endpoint that contains radio buttons. Unfortunately, I cannot modify the HTML content coming from this endpoint. My goal is to convert these radio buttons into regular b ...

List of React components created using Typescript

Struggling with rendering a list in React using Typescript. I'm new to Typescript and unsure how to properly pass props from App.tsx to Technology.tsx Vue JS Node JS Angular JS React JS Technology.tsx import React from 'react'; export ty ...

What steps can be taken to ensure that all object properties become reactive?

Let's dive into this simplified scenario: interface Pup { name: string; age: number; } const puppy: Pup = { name: 'Rex', age: 3, }; The goal here is to establish a reactive link for each attribute within the puppy object. The usua ...

React TSX file not recognizing JSON data stored in an HTML data attribute

I am having some trouble with implementing the password toggle component from the Preline UI. Here is how the component looks: "use client" import React, { ChangeEvent, MouseEventHandler, useEffect } from "react"; export default functi ...

I am seeking guidance for developing my own messaging platform, similar to Discord, using Typescript

Allow me to simplify this for you. This piece of code outlines TypeScript interfaces and namespaces for a WebSocket API that is commonly used in a chat or messaging system. It seems to define the format of messages being exchanged between a client and ser ...

The array value remains unchanged when included in the response

My goal is to send back the "projets" array within an expressJs route after fetching images for each item. However, when I return the response with the updated array, the newly added fields don't seem to be included. Note: When I log the added item, ...

How to use React hooks to flip an array

Is it possible to efficiently swap two items in an array using JavaScript? If we are dealing with a boolean, one could achieve this by: const [isTrue, setIsTrue] = useState(false); setIsTrue(!isTrue); However, what if we have an array? // Let's ...

Instructions on how to insert the meta tag with the attribute "http-equiv" set to "REFRESH" and the content "0; URL="somedomain"" into a division on a

Trying to send an ajax request to a page that includes the following meta tag: <meta http-equiv="REFRESH" content="0; URL=https://www.ohterDomain.com/help?nodeId=2&view=content-only"> After making a successful ajax call, the correct content is ...

Most effective method for initiating model class attributes

Is there a more efficient way to initialize model classes without explicitly defining each member as undefined? The original concept was to be able to simply use super(data); in extended classes. class Model { construct(data: any) { Object.ke ...

Achieving a delayed refetch in React-Query following a POST请求

Two requests, POST and GET, need to work together. The POST request creates data, and once that data is created, the GET request fetches it to display somewhere. The component imports these hooks: const { mutate: postTrigger } = usePostTrigger(); cons ...

Guide to changing the activation of Bootstrap popover on elements that are added dynamically

My popover functionality is triggered by a click action on a static element, revealing and hiding the popover. However, I am encountering an issue when dynamically generating new elements with the same functionality: $('.check-out-cell').click(f ...

What is the best way to conceal my class element if the data-reviews number is under 5?

I have been experimenting with basic JavaScript for the data-reviews="2" scenario and it worked successfully. However, what I am aiming for is to hide the entire <span> section when the value of data-reviews is less than 5 or any specific ...

Building an Express API using ES6 script: A Step-by-Step Guide

After creating a no-view REST API using the express generator, I decided to convert everything to ES6 script and compile it with Babel. However, upon entering localhost after the changes, an error message appeared: No default engine was specified and no ...

The code executes smoothly on my local machine, but encounters an error on Heroku: [TypeError: An invalid character is present in the header content ["Authorization"]] {error code: 'ERR_INVALID_CHAR'}

I am currently working on a chatbot project that utilizes the openAI API to generate responses based on specific prompts related to a particular topic. Everything works perfectly when I test the code on my local machine. However, upon deploying it to Herok ...