Retrieve the values of a dynamic JSON object and convert them into a comma-separated string using Typescript

I recently encountered a dynamic JSON object:

    {
    "SMSPhone": [
        "SMS Phone Number is not valid"
    ],
    "VoicePhone": [
        "Voice Phone Number is not valid"
    ]
}

My goal is to extract the values as a comma-separated string. The challenge here is that I do not know the key names beforehand.

The desired output should be: SMS Phone Number is not valid, Voice Phone Number is not valid

This is the code snippet I attempted:

let res = JSON.parse(Jsondata);
   res.forEach(element => {
    console.log(element)
    //logic
  });

However, upon running this code, I encountered the following error: https://i.stack.imgur.com/vxsFQ.png

Answer №1

It's important to clarify your objective in this situation. Keep in mind that using forEach on an object is not a valid approach since it is designed to iterate through array data. For the desired outcome, consider utilizing Object.entries() as demonstrated below.

const data = {
    "SMSPhone": [
        "SMS Phone Number is not valid"
    ],
    "VoicePhone": [
        "Voice Phone Number is not valid"
    ]
};

for (const [key, value] of Object.entries(data)) {
  console.log(`${key}: ${value}`);
}

Answer №2

response is a complex data type, so you cannot use forEach on it. To iterate over the values within an object, you can utilize a method like this:

for (const [key, value] of Object.entries(JsonData)) {
  console.log(value);
}

Read more about Object.entries here!

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

Traversing fields of a document within a Firestore collection using Angular

Attempts to retrieve the user's photoUrl based on their ID have been unsuccessful. Here is a snapshot of my firestore collection, can someone please guide me on how to access the photoUrl? https://i.stack.imgur.com/p2Zvm.jpg The main collection is &ap ...

Utilizing the MapToIterable Angular Pipe with TypeScript

Exploring the implementation of a pipe in Angular. Discovered that ngFor doesn't work with maps, prompting further research to find a solution. It seems that future features may address this issue, but for now, utilizing a mapToIterable pipe is the re ...

Will the component re-render before executing the next lines when using setState or dispatch with the useReducer hook?

Upon using the useState and useReducer hooks, I encountered an issue where any code lines following the state update function (setState, dispatch) would be executed in the subsequent re-rendering, with the previous state intact before the update. Essential ...

Creating and setting a selected option dynamically in Angular 2 for editing purposes

As I attempt to modify a user, I encounter a scenario where the user possesses a non-primitive array of machines. During editing, my goal is to generate new elements with select options and assign the selected value based on the user object: export class ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

Utilizing an array of data to create a complex structure with nested

In my Next.JS React project using TSX files, I have set up a data file like this: const fieldMapping = { category:[ { title: "Category 1", Subtitle: ["Category 1", "Category 2"], SubSubTitle: ["Category ...

Best practices for applying the Repository pattern within a NestJS application

After reviewing the NestJS documentation and examining their sample source codes, it appears challenging to implement a Repository pattern between the service layer and the database layer (e.g. MongoDB). In NestJS, database operations are executed directl ...

receiving null instead of an identifier

Attempting to perform an update operation in Angular. Upon submission after updating, a random number is displayed at the end of the API rather than the specific id number. The request URL appears as follows Request URL: http://localhost:4200/api/auth/rol ...

Need to import Vue component TWICE

My question is simple: why do I need to import the components twice in the code below for it to function properly? In my current restricted environment, I am unable to utilize Webpack, .vue Single File Components, or npm. Despite these limitations, I mana ...

Angular Material calendar tool customization for designated input

Is it possible to individually control the format of input for a datepicker without affecting the format for the entire module? <input matInput [matDatepicker]="dp" [formControl]="date" [format]="'DD/MM/YYYY'"> <-- Can this be done? < ...

Managing the re-rendering in React

I am encountering a situation similar to the one found in the sandbox example. https://codesandbox.io/s/react-typescript-fs0em My goal is to have Table.tsx act as the base component, with the App component serving as a wrapper. The JSX is being returned ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Implementing the strictNullCheck flag with msbuild

Can strict null checks be enabled when compiling using msbuild? I see in the documentation that the compiler option is --strictNullChecks, but I couldn't find any specific entry for it on the msbuild config page. Is there a method to activate this f ...

The Google Books API has encountered an authentication error with status code 401

Trying to access public data using the Google Books API locally: An error occurred with the authentication credentials. It seems that an OAuth 2 access token, login cookie, or another valid authentication credential is missing. For more information, visit ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

Error: The function setEmail is not defined. (In 'setEmail(input)', 'setEmail' is not recognized) (Cannot utilize hooks with context API)

App.js const[getScreen, showScreen] = useState(false); const[getEmail, setEmail] = useState(""); <LoginScreen/> <LoginContexts.Provider value={{getEmail,setEmail,getScreen,showScreen}}> {showScreen?<Screen2/>:<LoginScre ...

The ng2-chart library displays date in the form of a Unix timestamp

I have a date object imported from my database, but it is showing up as a Unix timestamp (-62101391858000). I know I can format the date using pipes like {{myDate | date:medium}}, however, I am using ng2-charts so I need to find a different solution. My ch ...

Show the alias of a type in Vscode Typescript instead of its definition

Here is some code that I am working with: type Opaque<T,U> = T & {_:U}; type EKey = Opaque<number,'EKey'>; type AKey = Opaque<EKey,'AKey'>; type PKey = Opaque<AKey,'PKey'>; let a = <PKey>1; ...

Ensure that missing types are included in a union type following a boolean evaluation

When working with typescript, the following code will be typed correctly: let v: number | null | undefined; if(v === null || v === undefined) return; // v is now recognized as a `number` const v2 = v + 2; However, if we decide to streamline this process ...

Using the watch flag in TypeScript across multiple projects - A comprehensive guide

In my project, I have the following scripts section in the package.json: "watch": "?", "build": "npm run build:compactor && npm run build:generator && npm run build:cleaner", "build:lambda": ...