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

Is it necessary to manually validate parameters in TypeScript when developing a library?

Understanding the basic workings of TypeScript, it's clear that TypeScript transpiles code to JavaScript without adding extra behavior like type checking during execution. For instance, function example(parameter: string): void { console.log(paramet ...

Azure function indicates a successful status despite receiving a result code of 500

I have an Azure function containing some logic with a basic try-catch structure (code shortened). try { // perform logic here that may fail } catch (ex) { context.log(`Logging exception details: ${ex.message}`); context.res ...

Angular 8: Issue encountered while resolving parameters for TextAreaEditorComponent

After upgrading angular to version 8.2.14, I attempted to convert the below code from a class to a component. However, I encountered the following error: ERROR in Can't resolve all parameters for TextAreaEditorComponent The issue seems to be with th ...

Struggling to chart out the post response in Angular 7

I am facing an issue while setting up a service on Angular version 7. The problem arises with the res.json() method, throwing an error stating Property 'json' does not exist on type 'Object'. Below is my service's code: import {In ...

The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes. My goal is to enhance the Angular HTTP client by adding custom headers. I envision creating a class like this, where I extend the Angular h ...

Definition of TypeScript array properties

Having some trouble creating a type for an array with properties. Can't seem to figure out how to add typings to it, wondering if it's even possible. // Scale of font weights const fontWeights: FontWeights = [300, 400, 500]; // Font weight alia ...

The function cannot be called because the type does not have the appropriate signature for invoking. The specific type lacks compatible call signatures, as indicated

Encountering an issue while attempting to utilize a getter and setter in my service, resulting in the following error message: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures 2349 t ...

After a duration of 4 minutes, an ERR_EMPTY_RESPONSE is thrown in response to the

My angular 5 node app involves sending a request to the server and waiting for a response. There are instances where the response takes around 5-6 minutes to arrive. However, an ERR_EMPTY_RESPONSE error is triggered by the http method after just 4 minutes ...

Creating a specialized Typescript deep partial type for specific attributes

I have a challenge in writing a utility type that takes an object as a generic parameter and a union of strings to recursively make specific properties optional. While it may sound simple, I encountered an issue that I need assistance with. Here is the uti ...

Invoking a nested class while declaring types in TypeScript

This is the specific format of data that I am in need of this.structure=[ { id: 1, name: 'root1', children: [ { id: 2, name: 'child1' }, { id: 3, name: 'child2' } ] }, { ...

Why is the bearing attribute important in determining the location of an object?

I have started using this plugin to enable GPS functionality in my app. If you are interested, the link to the plugin can be found here: https://github.com/mauron85/cordova-plugin-background-geolocation My question is about the bearing property of the lo ...

Selecting a single mat radio button from a group of radio buttons within a column in a Mat Table

How can I ensure that only one radio button is selected when setting the primary contact detail and saving it, as shown in (image 1)? After clicking the Save button, how do I display the saved details as shown in (image 2)? The selected radio button shou ...

What is the reason behind a tuple union requiring the argument `never` in the `.includes()` method?

type Word = "foo" | "bar" | "baz"; const structure = { foo: ["foo"] as const, bar: ["bar"] as const, baX: ["bar", "baz"] as const, }; const testFunction = (key: keyof typeof sche ...

Displaying data labels overlaid on top of data points in line charts

Currently, I am utilizing Angular2 along with ng2-charts to generate a line chart. My objective is to position the data labels directly above the points, similar to how they appear in the bar chart showcased in this image: bar chart I stumbled upon the ch ...

Is a donut chart graph visible on the webpage?

After successfully creating a bar chart, I decided to work on a donut chart using Angular and d3.js. However, despite creating the donut chart, I'm facing an issue with displaying it on the screen. The DOM shows that it is present, but for some reason ...

Can you explain the concept of injection context within Angular version 16 and later?

I have come across the term "Injection context" and am trying to understand what it entails. In Angular, there are several things that are connected to injection context: EnvironmentInjector#runInContext injectionContext runInInjectionContext inject() Fr ...

arranging data in html table columns using angular 2

I am facing a challenge where I require each column of a table to be sorted in ascending order every time it is clicked. The sorting logic implemented is a standard JavaScript method. While this method works well in most scenarios, it encounters issues whe ...

Is it possible to refresh the webpage in Angular when the tab is clicked?

Can someone help me find a solution to reload an Angular app's page when the user selects the browser tab? I've been exploring using window.location.reload() for this purpose, but I need guidance on triggering it specifically when the tab is sel ...

Switching Workspaces in Visual Studio

Is it possible to switch from an existing project to a new one in Visual Studio using NPM? ...

Tips on Configuring the Attributes of a TypeScript Object in Angular 2

A TypeScript class called Atom is defined as follows: export class Atom { public text: String; public image: boolean; public equation: boolean; } To create an object of type Atom class and set its properties, the following steps are used: atom: ...