Navigating any object array in TypeScript and retrieving its properties

Consider the following JSON data object:

    var dataObjects = [
         {
          "Name": "Date & Time",
          "Type": "Date",
          "Value": "2019-12-11"
          },
          {
          "Name": "Activity",
          "Type": "String",
          "Value": "ADD"
          }
      ]

I am looking to create a new JSON data array object based on the existing one, but with the date formatted differently from "2019-12-11" to "December 11, 2019".

I have attempted to achieve this by consulting various resources online, however, I keep encountering syntax errors in my code.

My understanding of Typescript and Javascript is limited, which is why I am seeking assistance as even seemingly simple tasks prove to be challenging for me. Your help is much appreciated.

        public FunctionA(dataObjects: any[]): object 
        {
           let returnObj: any = {}
           let returnObjArray: any = [];

           for(let obj in dataObjects){

             var dateValue = obj.Date;

             if(obj.Type == "Date"){
               dateValue = obj.Date.Format()
             }
             returnObj = {"Name", obj.Name, "Type": obj.Type, "Value": dateValue };
             returnObjArray.push(returnObj);
           }

           return returnObjArray;
        }

I recognize that the issue lies in specifying the type of the "any" array before using its properties. Despite attempting to declare it below, I continue to face errors:

    dataObjects: Array[{ Name: string, Type: string, Value: string }]

Answer №1

Below is a method to help you reach your objective:

 let dataEntries = [
    {
    "Title": "Date & Time",
    "Category": "Date",
    "Data": "2019-12-11"
    },
    {
    "Title": "Activity",
    "Category": "String",
    "Data": "ADD"
    }
]
type infoType = {Title: string, Category: string, Data: string};

function processData(dataEntries: infoType[]): infoType[] 
{
    let modifiedDataArray: infoType[] = [];

    dataEntries.forEach((entry:infoType)  => {
        if(entry.Category === "Date"){
        entry.Data = moment(entry.Data).toString("MMM dd, yyyy");
        }
        modifiedDataArray.push(entry);
    });
    return modifiedDataArray;
}

moment(entry.Data).toString("MMM dd, yyyy");
can be used to change the format of your date string to the desired one (employing the moment library).

Answer №2

This is the structure that should be followed:

Array<{ Name: string, Type: string, Value: string }>

Alternatively, you can use this format:

{ Name: string, Type: string, Value: string }[]

A more organized approach would be to define a type:

type MyObject = {
  Name: string,
  Type: string,
  Value: string 
}

Then utilize MyObject[] throughout.

Answer №3

If you're looking for a solid approach, consider crafting your own custom DataObject interface and leveraging the power of the map function to generate a new array.

interface DataObject {
  name: string;
  type: string;
  value: string;
}

var dataObjects: DataObject[] = [
  {
   "name": "Date & Time",
   "type": "Date",
   "value": "2019-12-11"
   },
   {
   "name": "Activity",
   "type": "String",
   "value": "ADD"
   }
]

function convertDate(date: string): string {
  // Insert your date conversion logic here.
  return date;
}

function convertDataObjects(dataObjects: DataObject[]): DataObject[] {
  return dataObjects.map(obj => {
    return {name: obj.name, type: obj.type, value: convertDate(obj.value)};
  });
}

console.log(convertDataObjects(dataObjects));

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

What is the proper type declaration for incoming data from the backend in my TypeScript code when using axios?

In the TypeScript code snippet provided, the type for 'e' (used in the function for form submission) has been figured out. However, a question arises if this type declaration is correct. Additionally, in the catch block, the type "any" is used fo ...

Guide on creating a universal template from a collection of interfaces

Two interfaces, AllTypes type: interface A { // ... } interface B { // ... } type AllTypes = A | B; How can I utilize generics to ensure that a function's argument is an object with either interface A or B? // pseudocode function test<T ...

What is the process for configuring a TimePicker object in antd to send a Date with UTC+3 applied?

I have Form.Item and a TimePicker defined inside it. I am using this form to send a POST request, but when I try to post 16:35, it gets sent as 13:35. The UTC offset is not being considered. However, the CreationTime works fine because it utilizes the Da ...

Angular allows for the dynamic updating of og meta tags

Sharing dynamic content on WhatsApp has been made possible through an API. By utilizing the angular Meta class in my component.ts file, I am able to dynamically update the default meta tag property in index.html with the latest content. ...

Error: When trying to run the `ng build` command in Git Bash, TypeScript module cannot be

When attempting to execute ng build using Git Bash, I encountered this error message, even though I had previously executed npm install -g typescript. Where should I place the typescript installation so that Git can detect it? Error $ npm install -g typ ...

Is there a possibility in TypeScript to indicate "as well as any additional ones"?

When working with typescript, it's important to define the variable type. Consider this example: userData: {id: number, name: string}; But what if you want to allow other keys with any types that won't be validated? Is there a way to achieve thi ...

Setting up an inline style @Input in Angular 2: A step-by-step guide

I am currently working on a component that needs to display random values, which will be generated randomly and passed through some @Input bindings in the template. Everything seems to be going well, but I am facing an issue when trying to link an @Input t ...

Using Angular/Typescript with @Output and Union return types

I have implemented several modal windows that allow users to select records from a paged list in the database. For example, there is a component called course.select.component.ts specifically for selecting courses. The modal window accepts an @Input() mul ...

Angular asynchronous operations are failing to complete within the specified time frame

Observations suggest that Angular's async from @angular/core/testing is not properly resolving timeouts in tests when a beforeEach contains async as well. Sadly, the bug cannot be replicated on Plunkr or JSFiddle platforms. To reproduce this issue ea ...

What is the best way to transpile TypeScript within the Astro framework?

Recently, I decided to dive into exploring Astro for a couple of upcoming projects. In my research, I delved into the script and typescript sections of the documentation (), as well as (). However, I found the workflow somewhat counterintuitive and struggl ...

Handling errors in nested asynchronous functions in an express.js environment

I am currently developing a microservice that sends messages to users for phone number verification. My focus is on the part of the microservice where sending a message with the correct verification code will trigger the addition of the user's phone n ...

Enhance user experience by enabling clickable links in Angular comment sections

Currently, I'm developing an application that allows users to add comments to specific fields. These comments may contain links that need to be clickable. Instead of manually copying and pasting the links into a new tab, I want the ability to simply c ...

Issue: Interface not properly implemented by the service

I have created an interface for my angular service implementation. One of the methods in the service returns an observable array, and I am trying to define that signature in the interface. Here's what I have so far: import {Observable} from 'rxj ...

Initiate a function once the innerHTML content in Angular has been completely loaded

I'm curious to know if it's possible in Angular to receive a notification when the Inner HTML has finished loading. I have a web application that retrieves an SVG image from a server and I need to display it as innerHTML in order to interact with ...

Passing an observable from parameters to a pipe in RxJS: A guide

Can someone help me with writing a TypeScript function like the one below: function abc(arg1, arg2, arg3) { pipe(arg1, arg2, arg3...); // or someSubject.pipe(arg1, arg2, arg3..) } I keep getting errors when trying to build the code. How can I success ...

XState: linking together multiple promises seamlessly without needing intermediate states

After reading the Invoking Multiple Services section, it seems that despite being able to invoke multiple promises, they appear to be triggered without waiting for the previous one to complete in my own tests. // ... invoke: [ { id: 'service1' ...

Before accessing the page, please ensure to make a double request

Encountered a weird issue, While inspecting the network tab in Chrome devtools, I noticed that my Vue app is making double requests to the same endpoint :/ Here's a snippet of my code: In the router section, I have a beforeEach function. When I navig ...

Utilizing an API to dynamically augment a JSON object with user input in Angular

Hello, I am working on adding an input value to an object property. The scenario is that a customer wants to add an item to their shopping cart, but before adding the item, they need to choose the size. I have the form set up with validation and can retri ...

Attempting to grasp the concept of implementing FormArray

When I execute the following code: this.formArray = new FormArray([ new FormControl(''), new FormControl(''), ]); formControlA() { return this.formArray.at(0); } formControlB() { return this.formArray.at(1); } and then use it ...

Are my Angular CLI animations not working due to a version compatibility issue?

I've been working on a project that had Angular set up when I started. However, the animations are not functioning correctly. The mat input placeholder doesn't disappear when typing, and the mat-select drop-down is not working. Here is my packag ...