The values of object keys are printed in a random order

Hey everyone, I have an object that looks like this

var dates = {
  '2021-09-15': 11,
  '2021-09-16': 22, 
  '2021-09-17': 38,
  '2021-09-18': 50,
  '2021-09-19': 65   
};

I am trying to display the values assigned to each key, so I attempted the following:

for( const date in dates ) {
  console.log(dates[date]);
}

Although it does print out the values, sometimes they appear in a random order. Any suggestions on how to address this issue would be greatly appreciated. Thank you!

Answer №1

Below are some methods you can use:

Object.keys: This method will provide an array of the property names of a specific object

var days = {
  '2018-08-06': 1,
  '2018-08-07': 2, 
  '2018-08-08': 3,
  '2018-08-09': 4,
  '2018-08-10': 5   
};

Object.keys(days).forEach(function (day) {
   console.log(days[day])
});

Object.values: Using this method will give you an array of the property values within the object

Object.values(days).forEach(function (day) {
  console.log(day)
})

Object.entries: You can utilize this method to get an array of arrays that contain key-value pairs

Object.entries(days).forEach(function (entry) {
  console.log(entry[1])
})

You can also make use of for in loop for similar functionality

for (let day in days) {
 if (days.hasOwnProperty(day)) {
   console.log(days[day])
 }
}

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

Unable to display the attributes of an object using console.log

I am attempting to log the properties of an object in TypeScript, but I am encountering issues. setTitleAndBody(result: { title: String; body: String; }) { console.log(result) console.log(result.title) } What's interesting is that if I only l ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

After I deploy my Next.js code to Vercel, including Google Analytics added by @next/third-parties, I am encountering an error that does not appear in development mode

Lately, I completed a next.js project and integrated Google Analytics using @next/third-parties/google. During development, everything worked perfectly, but upon deploying it to vercel.com, an error popped up. ` ./app/layout.tsx:3 ...

Limiting the number of items shown in the dropdown panel of an NgSelect

Currently, I am utilizing Angular ngselect to showcase a dropdown menu with multiple options. However, due to the limited screen space, I need to restrict the number of items visible in the dropdown to about 3, allowing users to scroll through the rest. W ...

The comparison between using Reflect.decorate and manual decorating in TypeScript

Here are two different decorators that I am using: import "reflect-metadata"; const enum MetadataTypes { Type = "design:type", Paramtypes = "design:paramtypes", ReturnType = "design:returntype" } function DecoratorA(target: any, key: string): void ...

What Causes a Mongoose Query to Result in an Empty Array?

Hello, I have reviewed similar questions regarding the issue I am facing with developing an API. Despite trying different solutions, none seem to resolve my problem. When handling request and response payloads in my API, everything seems to be working fin ...

Hold off until the operation finishes executing and then deliver Angular 6

Is there a way to delay the subscribe function until my logic is complete and the transform method has updated the keys object? transform(value: any, args:string) : any { let keys = []; this.http.get('src/app/enum-data/enum.json').subsc ...

The specified property is not found in the type 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; }>'

As I delve into utilizing React along with TypeScript and Material-UI components, I encounter some errors. One such error message pops up like this: The Property 'openToYearSelection' is not found on type 'IntrinsicAttributes & Intr ...

Create a custom data structure resembling a record, where certain keys are assigned specific value types

My objective is to establish a custom type resembling a record, where certain keys are designated for specific value types. The proposed object would look something like this: const o: TRec = { text: "abc", width: 123, height: 456, //...an ...

What is the method for retrieving the name of an object's property within an Angular template

I am trying to display the name of a nested object's property using Angular interpolation <ng-container ngFor="let item of saleDetailsAggegater.productMap | keyvalue"> <tr *ngFor="let qtyMap of item.value | keyvalue"&g ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

Does anybody have information on the Namespace 'global.Express' not having the 'Multer' member exported?

While attempting to set up an endpoint to send a zip file, I keep encountering the following error: ERROR in ./apps/api/src/app/ingestion/ingestion.controller.ts:46:35 TS2694: Namespace 'global.Express' has no exported member 'Multer'. ...

Is it acceptable to have an empty dependency array in React.useEffect?

Within my child React component, I receive an itemList prop from the parent component. This prop is an array of objects that contain data fetched from an endpoint. My goal in the child component is to enhance each object in the itemList array by adding mo ...

Clicking on the Angular custom accordion component does not trigger the expansion feature

I have developed a customized accordion component using Angular 9, but I am encountering an issue. Whenever I click on the accordion, only the first button's window expands while the others remain unaffected. To demonstrate the problem more effective ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

Troubleshooting the lack of success in enhancing global scope within Typescript

Currently, I am working on a microservices application where I have two very similar services that use practically the same packages. To perform some testing, I decided to add a function to the global scope and modified it slightly to prevent any TypeScrip ...

Angular - Implementing a debounce feature for event handling

Currently, I am utilizing the mouseenter and mouseleave events to control the opening and closing of my sidenav within the app. However, I have encountered issues because when hovering over the container quickly, these events are triggered multiple times ...

Storing data retrieved from a GraphQL response into the sessionStorage: A step-by-step guide

I am facing a challenge in saving my GraphQL response in sessionStorage to access it across different parts of the application without making repeated API calls. I am currently using the useQuery hook with a skip property to check if the data is already st ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

What is the process for building .ts components within a Vue application?

Looking to update an old project that currently uses the 'av-ts' plugin and vue-ts-loader to compile .ts files as Vue components. The project is running on Vue 2.4.2, but I want to upgrade it to version 2.6.14. However, since 'vue-ts-loader& ...