The error "Unable to access properties of undefined (reading x)" occurred while using the Array.prototype.find() method

In my Typescript project, I have an array of objects and I need to extract the value of a specific key based on a matching value in another key.

I want to retrieve the sheetId value of the object where the title matches the value of fileName.

Here is the object structure:

let list = [
  {
    "properties": {
      "sheetId": 1000297558,
      "title": "ser"
    }
  },
  {
    "properties": {
      "sheetId": 24134863,
      "title": "atr"
    }
  },
  {
    "properties": {
      "sheetId": 668935915,
      "title": "work"
    }
  }
]

This is the variable:

let fileName = 'atr'

What I want to retrieve:

let testId = 24134863

I have tried using the map method to match the values, but I'm unable to extract the key:

let sheetFile = list.map((elem: any) => elem.properties.title == fileName)

Update:

To find the value of sheetId, I am using the find method:

let sheetId: number = list.find((elem: any) => elem.properties.title == fileName).properties.sheetId

However, I'm encountering an error:

Error: Cannot read properties of undefined (reading 'properties')

My issue: how can I handle the undefined value or assign it a default value like 0?

Answer №1

To extract your value using dot notation, you can utilize the .find method.

const keyword = 'atr'
const data = [
  {
    "properties": {
      "sheetId": 1000297558,
      "title": "ser"
    }
  },
  {
    "properties": {
      "sheetId": 24134863,
      "title": "atr"
    }
  },
  {
    "properties": {
      "sheetId": 668935915,
      "title": "work"
    }
  }
]

const output = data.find((item) => item.properties.title === keyword).properties.sheetId;

console.log(output);

Answer №2

To start, the initial step is to use the filter method to identify matches.

Following that, utilize the map method to extract data from the matched items.

const dataList = [
  {
    "properties": {
      "sheetId": 1000297558,
      "title": "ser"
    }
  },
  {
    "properties": {
      "sheetId": 24134863,
      "title": "atr"
    }
  },
  {
    "properties": {
      "sheetId": 668935915,
      "title": "work"
    }
  }
]

const fileName = 'atr'

const testId = 24134863

const selectedSheet = dataList
  .filter((item) => item.properties.title === fileName)
  .map((item) => item.properties.sheetId)
 
console.log(selectedSheet)

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

Angular 4 - The Promising Outcome: How to Retrieve the Value upon Completion

Is there a way to retrieve a value from a promise and store it in a global variable? I've been attempting to accomplish this, but the global variable remains undefined. import { Injectable } from '@angular/core'; import {ActivatedRouteSnap ...

Setting up Mailgun with TypeScript on Firebase Cloud Functions

Currently, I am working on a Cloud Function within Firebase to integrate with Mailgun for sending emails, following the guidelines provided in the Mailgun documentation. My challenge lies in implementing this functionality using TypeScript, as I have been ...

Using JavaScript to utilize a variable containing a .match method with Regex Expression

Recently, I started delving into the world of regex with the aim of incorporating variables in my matches. Imagine I have a string that reads "Total: $168" My goal is to extract just the numerical value; 168. This is what I currently have: totalCost = t ...

"Creating a Miniview Panel on a Fabric Canvas: A Step-by-Step Guide

Is there a way to add a mini view panel to my Fabric Canvas like shown in this image MiniView Panel? I want a panel in the corner of my canvas that displays the entire layout. Similar to the panel on this website . ...

Utilizing the Jquery hover feature to reveal or conceal an element

My Hover function is designed to display and hide sub menus when a person hovers on them. The issue I'm facing is that the menu disappears when I move the mouse down towards it. Can someone help me identify what I am doing wrong here? ...

struggling to retain data within scope when utilizing localstorage in angular

Currently, I am utilizing the fileReader to read a file, save the image in localStorage, and then display it on the view. In the controller: angular.module('App')controller('publsherProfileEditCtrl', ['$rootScope', '$sc ...

When submitting, Redux objects are being submitted with empty values

Whenever I try to submit my form, the object is being submitted empty. This was confirmed using the redux dev-tool, where it shows that the object is empty upon submission. The expected behavior is for a card to appear on the DOM with the information enter ...

Describing an Object with some typed properties

Is there a method to specify only a portion of the object type, while allowing the rest to be of any type? The primary objective is to have support for intelliSense for the specified part, with the added bonus of type-checking support. To demonstrate, let& ...

Navigating Divs Using jQuery

I am working with a class that has multiple divs, each with a unique id attached to it. I am using jQuery to dynamically cycle through these divs. This is a snippet of my HTML code: <div id ="result">RESULT GOES HERE</div> ...

Preventing the addition of duplicate items to an array

My current challenge involves pushing containers into an array in my JavaScript code. However, once a container has been pushed, I want to prevent that same one from being pushed again. If you'd like to take a look at the JSfiddle where I'm work ...

Automating Python functions with Selenium API after exceeding page load time

I am currently working on a Python script that uses Selenium with the Chrome webdriver. Occasionally, the script gets stuck while loading pages because of JavaScript trying to load in the background. I have tried using the line: driver.execute_script("$(w ...

Ensure that the page is fully loaded before proceeding with the redirection

I have a webpage that currently performs a small task before redirecting to a third-party site. The redirection is initiated by using Response.Redirect(); Now, I am looking to integrate another function using JavaScript this time. To add the JavaScript ...

Decode a JSON list

I am currently experimenting with deserializing JSON data in C# using the Newtonsoft namespace. Below are the classes I am working with: class finalResponse { public string category { get; set; } public Description description { get; set; } ...

The correct way to handle JSON parsing in the background using Flutter

Currently, I am venturing into the world of Flutter and facing challenges with JSON parsing. Initially, I followed the recipe for data fetching which worked smoothly with my custom JSON. However, when I transitioned to background parsing (which is more be ...

Why does the Formik form only validate after the second button click in this React Hooks, TypeScript, Formik, NextJS setup?

Looking for fresh perspectives on my code. The issue lies in the fact that it takes two submission attempts to validate the data inputted into a form successfully. It appears that the post request to Airtable happens before the validation schema, resulting ...

Ways to determine changes made to a table in MSSQL

What is the most efficient method to determine if a table or row in MSSQL (using Node.js) has been modified? I am looking to verify whether my database has been updated within the past 30 minutes. If no updates have been made in the last half hour, I pla ...

Asking for an API request in python that necessitates an oauth token

As I work on a program to send data to a specific URL and receive a response, I encountered an issue while using Python. The problem arose when trying to include a token in the request as required by Postman, resulting in a [401] response. The main obstac ...

What is the best way to leverage local storage/memory to save information for my text-based RPG game?

Currently, I am in the process of creating a text-based RPG on Codecademy. However, I am facing a challenge when it comes to implementing a save/load system using JavaScript/HTML. My idea is to create a system where players can type "save" into a prompt, ...

What would be an effective method for sending a multitude of parameters to a controller?

I am currently working on an application that utilizes Java with the Spring framework and Javascript with AngularJs framework. The application features a table displaying a list of objects along with two text fields for filtering these objects. The filteri ...

Issues arising from the event target

What is the reason behind this code functioning successfully only when the alert function is called? The color changes after closing the alert box, but if the line with the alert command is commented out, nothing happens. function setLinkColor(el) ...