Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implementation of a function called shiftKeyToLastPosition(keyname) for this purpose.

I attempted to use methods such as deleting and re-appending, as well as the reduce method, but none of them provided the desired outcome.

Answer №1

If all your values are strings, you can give this a try:

const source = {
  'Domestic': '1',
  'NONE': '0',
  'Wild': '2',
};

const { NONE, ...dest } = source;
dest.NONE = source.NONE;

console.log(dest);

In this code snippet, we create a new object without the 'NONE' key and then add the 'NONE' key at the end.

According to the ECMAScript 2015 specification, when traversing an object with string keys, the keys will be returned in the order they were inserted.

Note: This assumes that there are only integer and string keys, no Symbol keys.

Answer №2

According to proxima-b, there is no deterministic way to order an object.

However, you can create a helper function that allows you to specify the order in which key/value pairs are displayed. The beauty of Typescript is that you can achieve this in a type-safe manner!

const myObject = {
  'hello3': 'Value 3',
  'hello1': 'Value 1',
  'hello2': 'Value 2',
  'hello4': 'Value 4',
} as const;

function orderObjectToArrayKeyValue<Obj>(obj: Obj, orderKeys: { [key in keyof Obj]: number }): { key: keyof Obj, value: Obj[keyof Obj] }[] {
  return Object
    .entries<number>(orderKeys)
    .sort(([, order1], [, order2]) => order1 < order2 ? -1 : 1)
    .map(([key]) => ({ key, value: obj[key as keyof Obj] }) as { key: keyof Obj, value: Obj[keyof Obj] });
}

For example, if you use the following:

console.log(orderObjectToArrayKeyValue(myObject, {
  hello1: 1,
  hello2: 2,
  hello3: 3,
  hello4: 4,
}));

You will receive:

[
  {
    "key": "hello1",
    "value": "Value 1"
  },
  {
    "key": "hello2",
    "value": "Value 2"
  },
  {
    "key": "hello3",
    "value": "Value 3"
  },
  {
    "key": "hello4",
    "value": "Value 4"
  }
]

Using your preferred framework, it's simple to iterate over this array and display the values (and optionally use the keys).

Check out the live example (press enter while focusing the left side and it'll run the code, the output will be displayed in your console).

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 preventing me from making an inline call to res.json?

In my expressjs application, I encountered an issue with inlining a callback when using the res.json method to respond with a database document. While inlined calls to console.log worked fine, the program failed when I attempted the same approach with res. ...

Node.js is facing a problem with its asynchronous functionality

As a newcomer to node, I decided to create a simple app with authentication. The data is being stored on a remote MongoDB server. My HTML form sends POST data to my server URL. Below is the route I set up: app.post('/auth', function(req, res){ ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Transforming a two-column text document into a set of key-value pairs

Recently, I've been diving into the world of Node.js and Express. My current challenge involves converting a text file into key-value pairs. The approach I'm taking with my staircase program is as follows: https://i.sstatic.net/GPs200IQ.png Th ...

Why does Javascript in Angular throw an exception when using value, match, and replace functions together?

I have a small JavaScript function that I would like to implement in an Angular service or controller. function cprCheck(frm) { var cpr = frm.cpr.value; if (cpr.match(/[0-9]{6}\-[0-9]{4}/)) { cpr = cpr.replace(/\-/g, ""); var chk = 0; ...

How can images from a dynamic table be converted to base64 format in Vue.js and then sent in a JSON file?

Hello everyone, I'm facing an issue with a dynamic table where I need to add multiple rows, each containing a different image. I attempted to convert these images to base64 format and save them in a JSON file along with the table data. However, the pr ...

Capture a screenshot of an embedded object and include it in an email using the mailto function

Is there a way to capture a screenshot of a flash object on a webpage and then send it via email using a mailto: form submission to a designated address? I have attempted to use different JavaScript techniques, but none seem to be successful. Appreciate a ...

How can I reload a form page in Angular 9 after making a POST request with HttpClient?

I'm currently working on an Angular 9 application and am facing an issue with refreshing the page after making a POST request using HttpClient. Below is my form and its corresponding component: <form #myForm="ngForm" (ngSubmit)="save(myForm)"> ...

The functionality of a button within a web component is restricted to only trigger the click event once after it has been

I am facing an issue with my class that includes three buttons for navigating the app. The event listeners I add to these buttons in the connectedCallback method only work once. When I click one of the buttons, like the next button, it changes the attribut ...

Is it possible to disable a function by clicking on it?

I currently have a website that is utilizing the following plugin: This plugin enables an image to be zoomed in and out through CSS transforms, with default controls for zooming in and out. My goal is to incorporate a reset button that returns the image ...

Using Angular 4 with Semantic-UI for Dropdown menus

Currently, I am in the process of implementing an Angular directive to handle Semantic UI dropdown. My setup includes Angular (4.3.3), jQuery (3.2.1), and Semantic UI (2.2.13) installed via npm. To make these libraries work together, I made modifications ...

Exploring different approaches to recreate the functionality of promise.allsettled by utilizing async.each

I previously had a code snippet containing Promise.allSettled(payoutPromises); Unfortunately, it did not function properly on our server due to its nodejs version being 10. After consulting some blogs for guidance, I came up with the following alternativ ...

What is the best way to create a collage of images with a random and unique arrangement?

Recently, I stumbled upon a website and was intrigued by the unique effect of images randomly appearing on the screen. I'm curious about how this effect can be achieved. Is it possible to use CSS Grid to divide the screen and designate some grid ite ...

After clicking the create button in AngularJS, the ngModel values become empty

My form has been simplified by using ngRepeat to create the input fields. The attributes for each item are defined in my controller. Below is the code for the ModalCtrl: ... $scope.form = [ { label: 'First Name', fieldType: 't ...

Collaboratively accessing a shared constant in two separate JavaScript files

I am diving into the world of JavaScript and Node.js. I am currently experimenting with Puppeteer to extract the text value of a tag and store it in a constant variable. However, I am encountering difficulties when trying to integrate this value into my ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

Adding a specialized loader to vue-loader causes issues when the template contains personalized elements

My vue2 component is structured as follows: <template> <p>Hello world</p> </template> <script> export default { name: 'Example' }; </script> <docs> Some documentation... </docs> In addition, I& ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

Updating the image sources of a group of image tags with a predetermined list

Looking to update a series of image source references within a specific div tag. For example: <!-- language-all: lang-html --> <div id="Listofimages"> <img src="images\2page_img_3.jpg"> <img src="images\2page_img_3 ...

Why is it impossible for me to delete the class / property of this object?

Within a series of nested divs, there are additional divs containing multiple imgs. The goal is to cycle through these images using CSS transitions. To achieve this, a JavaScript object was created to track the divs, sub-divs, and images. Three arrays were ...