Exclude undefined values from an array in React using JavaScript

I am working with an array of objects that contain content types

const contentTypes = [
    {
        "contentType": {
            "content_type_id": 2,
            "content_type": "image",
        },
    },
    {
        "contentType": {
            "content_type_id": 3,
            "content_type": "video",
        },
    },
    {
        "contentType": {
            "content_type_id": 1,
            "content_type": "audio",
        },
    },
]

In my function setType, I aim to match elements and set the content_type_id to content_type. The values are then converted to strings.

const setType = (selectedType) => {
    _setType(selectedType)
    const typeString = contentTypes.find((item) => {
        return item.contentType.content_type_id === selectedType
    }).contentType.content_type;
    onTypeChange(typeString)
}

The challenge arises when there is an element in the array contentTypes missing the content_type_id and content_type, resulting in the error:

Unhandled Runtime Error TypeError: Cannot read property 'contentType' of undefined

You can view the code on jsFiddle here => https://jsfiddle.net/9x426Lv7/2/

How can I handle this scenario in the find method? Are there alternative approaches to address this issue?

Answer №1

Hello Koala7, here is a suggestion for you to try out:

function updateType(selectedType) {
    setType(selectedType);
    let type = contentTypes.find((item) => {
        return item.contentType.content_type_id === selectedType
    });
    let typeString = type ? type.contentType.content_type : null; // You can assign another default value instead of null
    onTypeChange(typeString);
}

Answer №2

It seems that your find function is failing to retrieve a value and instead returning undefined. Make sure to validate whether the selected type you are attempting to locate actually exists.

Answer №3

what do you think?

function setContentType(selectedType) {
    const type = contentTypes.find((item) => {
        return item.contentType.content_type_id === selectedType;
    });
    if(type) {
     return contentType.content_type;
    }
    return null;
}

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

Exploring JSON data in AngularJS

After creating a new Angular App, I decided to store some data in a JSON file. My main concerns are where to best store the .json file within the app and how to access it. Currently, I am facing this error in my Chrome console: GET http://localhost:8000/t ...

Guide on adding a button to a mat-table in Angular

I am looking to add a delete button or an Angular trash icon to a mat-table in an Angular application. Can anyone guide me on how to achieve this? Here is my current table code: <mat-table #table [dataSource]="ELEMENT_DATA"> <ng-container cdk ...

What is the best way to transfer data from Material UI to Formik?

I'm facing an issue when trying to integrate a Material UI 'Select' component into my Formik form. It seems like I am unable to pass the selected values from the Material UI component to Formik's initialValues. const [selectedHours, se ...

What is the most efficient way to organize a dynamic array with jQuery?

In my jQuery code, I have created two empty arrays and used AJAX to assign values to them. The issue is that the values assigned by AJAX are random, so I need to display them in an efficient way. Here's the code snippet I'm using: Code:- <se ...

Enhancing Security and Improving Performance with Subresource Integrity and Cache Busting Methods in

I am in the process of integrating Subresource Integrity and cache busting for my application's static assets like stylesheets and JavaScript files. Currently, I am using PHP with Twig templates. While I am aware of tools available for generating has ...

Contrasting the methods of invoking functions

It has come to my attention that (especially in the realm of React) there are multiple ways to invoke a function. I can point out: onClick={myFunction} onClick={myFunction()} onClick={()=>myFunction} onClick={()=>myFunction()} /*I'm uncertain if ...

socket.io, along with their supporting servers

Can socket.io function separately from being the webserver? I prefer to utilize an external webserver, but in order for it to function properly I require /socket.io/socket.io.js. Is there a method other than duplicating[1] this file? I want to avoid comp ...

I am curious about the inner workings of the `createApplication()` function in the ExpressJS source code. Can you shed some light on

My goal is to deeply comprehend the inner workings of the Express library, step by step. From what I gather, when we import and invoke the 'express()' function in our codebase, the execution flow navigates to the ExpressJS library and searches fo ...

What is the best way to automatically add a date and timestamp to every new entry?

I am currently working on a project that utilizes AngularJS and Ionic frameworks. The main feature of the project will involve users inputting data to create a list, and allowing any user to comment on each item in the list. One challenge I have encounter ...

Avoiding the repetition of CSS animations during Gatsby page hydration

I am facing an issue in Gatsby where I have an element with an initial CSS animation. It works perfectly when the static site loads, but after hydration, it keeps repeating. Is there a way to prevent this from happening? Below is my styled components code ...

Enhance your ChartJS visualizations by updating your charts with multiple datasets

Seeking a way to update both datasets in my chart without having to destroy and recreate it. chart2 = window.TrafficChart; chart2.data.labels = data.timestamps; console.log(data.traffic_tx); chart2.data.datasets[0] = data.traffic_rx; chart2.data.d ...

I am encountering an issue where JSON.parse is returning undefined when trying to

Upon receiving a string from my server, I am attempting to parse it into a JSON object. Here is the string and relevant code snippet: stringToParse = "\"{'female': 16, 'brand': 75, 'male': 8}\"" d ...

Leveraging Node.js to fetch data from a third-party website API using JSON

This particular code is currently not functioning properly as it is unable to retrieve an address from an external website We need the "result" value that is present in that json file. Is there a straightforward solution for this issue, such as enabling ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

Transforming a circular data structure into JSON format within Firebase

https://i.sstatic.net/BhQtp.png The data returned from firebase is causing an issue when I try to stringify it: JSON.stringify(data) // where data represents the returned object This results in the error: TypeError: Converting circular structure to JSON ...

How can I use HTML and Javascript to toggle the visibility of a 'select' element, like a dropdown menu

After adding a dropdown and label within a div, I expected them to hide and unhide when the div is manipulated with a function. However, it seems that this functionality is not working as expected. function ToggleDiv(DivID) { if (document.getElementBy ...

Creating a table with React components to display an object

I'm a React novice struggling to render an object in a table. While I can access the ctx object using console.log, I can't seem to display it in the table on the browser. Any help and advice would be greatly appreciated. The code snippet is provi ...

Adding a class to the body element in an HTML file using AngularJS

Greetings! Currently I am in the process of developing a web application using AngularJS SPA, which supports both English and Arabic languages. I am facing an issue with adding RTL and LTR properties by applying classes to the body HTML element in my app.j ...

The AngularJS promise is not resolving before the external Braintree.js script finishes loading after the HTML content has been fully

Using an external braintree.js script is necessary to generate a payment widget, and unfortunately I have no control over it. The code that needs to be included in my .html page is as follows: <div id="myClient" ng-show="false">{{myClientToken}}&l ...

Issue with radio button: checked property remains unchanged

There seems to be an issue with a div element where a table is being appended with input elements of type radio. The checked property does not change when clicked. What could be causing this problem? <input type="radio" id="radHalf0" name="grp0" class= ...