Exploring object traversal in Typescript

Why is the output undefined? I even tried giving timeObject a type of any, but it still doesn't produce the expected result.

const timeObject = {
  'On web close': 0,
    '10 secconds': 10000,
    '8 hours': 28800000,
    '12 hours': 43200000
}

 let timeToString = (time: number) => {
  Object.keys(timeObject).map((key) => {
    if (timeObject[key] === time) {
      return timeObject[key]
    }
  })
}

console.log(timeToString(10000))

Answer №1

It is important to note that the timeToString function does not return anything, and it might be more appropriate to use find instead of map in this case. When using map without an else condition, you may end up with a result like

[ undefined , "10 seconds", undefined, undefined]

However, by making these adjustments in the code snippet below, you can ensure a correct output:

   let timeToString = (time: number) => {
       return Object.keys(timeObject).find((key) => {
            if (timeObject[key] === time) {
                   return timeObject[key]
         }
   })

How does it work ?

Object.keys(timeObject) will provide an array of keys such as

[ "On web close", "10 seconds", "8 hours", " 12 hours"]

Afterwards, you can apply various array methods to calculate your desired result and make sure to return this result from the function.

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

How can I designate inner schemas as optional in Ajv?

Here is a sample schema using ajv (v8.11.2) import Ajv, { JSONSchemaType } from "ajv"; interface MyType { myProp?: OtherType; } interface OtherType { foo: string; bar: number; } const otherSchema: JSONSchemaType<OtherType> = ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

What is the best way to efficiently filter and process two arrays of objects?

I am struggling to efficiently match and update objects from 2 arrays with different key combinations. Despite trying various .filter combinations, I have not been successful yet. My goal is to update the masterList based on the selectionList. for (let se ...

Can Vue props accept a generic type argument?

Currently, I have a basic component that is receiving the following props: props: { options: { type: Array as PropType<unknown[]>, default: () => [] }, labelKey: { type: String, default: "label" ...

Angular - Leveraging Jest and NgMocks to Mock Wrapper Components

Within our project, we have implemented a feature where user roles can be assigned to various elements in the application. These roles determine whether certain elements should be disabled or not. However, due to additional conditions that may also disable ...

What is the rationale behind TypeScript's decision to implement two checks for its optional chaining and null-coalescing operators during compilation?

What is the reason behind the way the TypeScript compiler translates its optional chaining and null-coalescing operators, found here, from: // x?.y x === null || x === void 0 ? void 0 : x.y; // x ?? y x !== null && x !== void 0 ? x : y as opposed ...

The issue with zone.js remains unresolved

Since updating to the most recent version of Angular cli, I have encountered an error when trying to run ng serve: ./node_modules/@angular-devkit/build-angular/src/webpack/es5-polyfills.js:106:0-37 - Error: Module not found: Error: Can't resolve &apo ...

Angular's DecimalPipe will truncate any strings that exceed 10 digits

Using the decimal pipe to format numbers in an input field value| number:'0.0-6': 'en-us' When working with numbers containing more than 10 digits, it displays as follows: For 11111111111.123456, it formats to 11,111,111,111.123455 ...

Navigate using an abstract data type

I am looking to transmit abstract data (In Angular 4 or 5) from one component to another without it being visible in the url. Currently, I am using the following method: let navigationExtras: NavigationExtras = { queryParams: { "firstname": "Nic ...

What is the best way to bring in a .obj file in a ReactJS project while utilizing TypeScript?

Currently working on a React project that involves typescript implementation. I found the need to import a .obj file, which led me to importing the threejs library alongside the react-three-fiber library in the following manner: import React, { use ...

What is the best way to prevent users from entering a zero in the first position of a text box using JavaScript

Although I am aware this may be a duplicate issue, the existing solution does not seem to work for me. The field should accept values like: valid - 123,33.00, 100,897,99, 8000 10334 9800,564,88.36 invalid - 001, 0 ...

Svelte: highlighting input text when selected

Is there a way to select the text of an input element when it is focused using bind:this={ref} and then ref.select()? It seems to only work when I remove the bind:value from the input element. Why is that the case, and how can I solve this issue? Thank yo ...

Problem with timing in token interceptor and authentication guard due to injected service

Currently, I am facing an issue where I need to retrieve URLs for the auth service hosted on AWS by reading a config.json file. In order to accomplish this, I created a config service that reads the config file and added it as a provider in app.module. Eve ...

Angular 2 Error: TS2322 - The type 'Subscription' cannot be assigned to the type 'Observable<MouseEvent>'

I have implemented the click-outside directive using this plunk --> http://embed.plnkr.co/v7BMUv/ But when I try to compile my TypeScript code, I encounter the following errors: Error TS2322: Type 'Subscription' is not compatible with type & ...

Angular component unable to retrieve array data from Angular service

I've developed an Angular service that serves as a middleman for fetching data from a database. Here's the code: export class WebService { constructor(private http: Http, private datePipe: DatePipe) { this.getStatsbyDate(this.datePipe.transf ...

ng-click-outside event triggers when clicking outside, including within child elements

I am looking to trigger a specific action when I click outside of the container. To achieve this, I have utilized the ng-click-outside directive which works well in most cases. However, there is one scenario where an issue arises. Inside the container, the ...

Circular dependency has been identified in Typescript as services are mutually calling each other

Within my application, I have 2 key service components: PromiseService.service.ts (which manages defer calls and asynchronous calls) @Injectable() export class PromiseService { constructor(private staffservice: StaffService) {} defercall(asyncCall ...

Exploring the capabilities of utilizing Leaflet in conjunction with Ionic2 using typescript

Being a beginner in the world of Ionic2 and Angular2 using typescript, my goal is to develop a mobile application that can run on both iOS and Android platforms. I have decided to integrate a map into my app, and after some research, I came across Leaflet ...

Export interface for material-ui wrapper to cast any type in TypeScript (React)

I work with React using TypeScript. Recently, I encountered an issue with exporting. I'm creating an interface that encapsulates components from Material-ui. Here is a simplified example: Wrapping.tsx import { default as Component, ComponentProps ...

What methods does VS Code use to display type errors in TypeScript given that TypeScript requires compilation?

TypeScript is a language known for being statically typed, giving it the ability to verify types during the compilation process and translate the code into JavaScript. Considering this, how is it possible for VS Code to detect type errors without the code ...