Troubleshooting Identifier Expected error in TypeScript while iterating through a JSON array

I am currently attempting to loop through a JSON array using TypeScript.

To help with comprehension, I have created a simple example involving a person interface.

However, I am encountering an issue with the line:

isArray(curr[k]) ? curr.[k]?.[0] : curr[k],.

ERROR: Identifier expected

Here is the code snippet in question:

import { isArray } from 'lodash'; 

const myObj = {
  "allData" :{
   "person" : [
    {
        "name":"John", 
        "age":30, 
        "email":"djsbjb"
    },
    {
        "name":"rohit.sharma.my.name", 
        "age":20, 
        "email":"fdbfhdbfn"
    }
   ]
  }
};

interface Person {
  name: String,
  age: number,
  email?: String
}

const example = (
  person: Person
) => {
  //rohit,sharma,my,name"
  const k = myObj.allData.person[1].name.split(
    '.'
    ) as (keyof typeof person)[];

  console.log(`output of k: ${k}`);
  const curr = { ...person};
  console.log(`output of curr: ${curr}`);
  if (!curr) {
    return;
  } 

  const ans =  k.map((k) => 
    isArray(curr[k]) ? curr.[k]?.[0] : curr[k],
  ); 

  return ans;
}

Answer №1

Using optional chaining to access array indices is not the correct syntax:

Consider this example:

const object: { [key in string]?: string[] } = { key: ['a'] }

const value = object.key?[0] // this is invalid

Instead, you should use `&&` to conditionally access array elements only if the array is not null or undefined:

const object: { [key in string]?: string[] } = { key: ['a'] }

const value = object.key && object.key[0]

In your case, update it as follows:

  const ans =  k.map((k) => 
    curr[k] && isArray(curr[k]) ? curr[k][0] : curr[k],
  ); 

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

Removing items from an array in Angular when a checkbox is checked

I'm looking to iterate through a checklist and remove completed items from the array. Here's my current code: app.controller("MainController", ["$scope",function($scope) { $scope.list = [{ text: 'Figure your stuff out', done: ...

A guide on specifying a generic type while exporting a component with generic type

Currently, my implementation of react components uses typescript. An issue I am encountering involves defining a generic type. Below is an excerpt showcasing the problem: interface Props<T> { classes: { [className in keyof typeof styles]: string } ...

What could be the reason my mat-form-field is not displaying the label?

I'm currently working on a project using Angular Material to build a web page. I am facing an issue with the mat-form-field component as the label is not displaying, and I can't figure out why. Any assistance would be greatly appreciated. Thank y ...

Is there a more efficient way to handle post data without increasing its size when encoding JSON within a URI

I have a significant amount of data to post, and it needs to be minimized for performance reasons. Initially, my data consists of JavaScript objects which I then convert to JSON format before sending it via POST request. The issue is that my data include ...

Transform a JSON string value to an integer

Is there a way to easily convert a string value into an integer when it's from a JSON document? JSON Example: [ { "date": "23.07. 16:59", "odd": "3.50", "change": "+0. ...

Is your JSON object receiving extraneous elements?

I received the following JSON output: {"OrderSummary":"[ {\"ProductQuantity\":\"1\", \"ProductName\":\"Wine\", \"Sellerid\":\"2\", \"ProductCost\":\ ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

Determine rest parameters based on the initial argument

Struggling to generate a solution that infers the arguments for an ErrorMessage based on the provided code input. ./errorCodes.ts export enum ErrorCodes { ErrorCode1, ErrorCode2, ErrorCode3 } ./errorMessages.ts export const ErrorMessages = { [Err ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

What is the method for retrieving elements from an array?

I'm currently working on a shell script that utilizes getopt to take command line arguments. While my script is functioning as expected, I am facing an issue with handling a special case where one specific argument can be submitted multiple times. Th ...

There was an unexpected error: The module "@angular-devkit/build-angular" could not be located

After entering the terminal commands ng server or ng serve, I encountered the following problem: An unexpected error occured: Module "@angular-devkit/build-angular" could not be located ...

The element is implicitly assigned an 'any' type as the expression of type 'string' is unable to be used as an index within the type '{...}'

Trying to improve my react app with TypeScript, but encountering issues when typing certain variables. Here's the error message I'm facing: TypeScript error in /Users/SignUpFields.tsx(66,9): Element implicitly has an 'any' type becaus ...

The ng-bootstrap modal fails to appear when incorporating [formGroup]="FormName" or formControlName="elementName"

Utilizing ng-bootstrap to create a popup modal has been a challenge for me. When I import FormsModule and ReactiveFormsModule in src/app/modal-basic.module.ts, the code inside it looks like this: import { NgModule } from '@angular/core'; import { ...

Tips for sending data through an API in an AngularJS application within an Ionic framework

Being new to this field, I require some assistance. I need to send data to an API, but I am struggling with the process. Can someone please guide me on how to do this? The API link is: Below is the JSON format in which the data needs to be sent: { "er ...

Launching a Material UI Modal nested within a parent component

I have a table displaying various teams. Each row in the table has a menu option that, when clicked, should open either a modal or a dialog box. I want to keep the table, menu functionality, and modals as separate components for better organization. Here&a ...

React-router-dom PrivateRoute component version 6.8.0

I have created a custom PrivateRoute for my chat app. This is how my PrivateRoute looks: import { useState, useEffect } from 'react'; import { Route, Navigate } from 'react-router-dom'; import axios from 'axios'; interface Pr ...

The mistake occurred due to the inclusion of 'mongoose/dist/browser.umd.js' in the file './config/mongodb/index.ts'

I successfully developed my custom application using next.js version 14 and mongoose version ^8.4.4, which functions flawlessly on my local machine. However, when attempting to deploy the application on Vercel, I encountered the following error in the con ...

What is the process of obtaining a Java class from a Java type array in Kotlin?

When dealing with pojo classes: //java MyClass.getClass(); //kotlin MyClass::class.java But how can we retrieve the class from an array? //java MyClass[].class; //kotlin ??? The MyClass[]::class.java approach does not seem to work. ...

An issue has been identified in the node_modules/xterm/typings/xterm.d.ts file at line 10, causing an error with code TS1084. The 'reference' directive syntax used

In my project, I have integrated xterm into Angular5. However, I am encountering an error when trying to run the application. Upon executing ng serve, I am facing the following error: ERROR in node_modules/xterm/typings/xterm.d.ts(10,1): error TS1084: In ...

Mastering the art of chaining HTTP requests with RxJS for optimal results

I have a task that involves making multiple HTTP calls sequentially, examining the result of each call before proceeding to the next one. Depending on the response, I may need to display a message, continue to the next call, or break the chain. Additionall ...