Order the JavaScript object by its value if the keys are numerical

I'm currently working on a project using InertiaJS.

I have a PHP array that I pass as a prop to Vue and display it as a select box. Here's what the object looks like in JavaScript:

{
  1: "Vexapa",
  5: "Linga & Satro",
  6: "Feearlees",
  7: "Abbaga, Sort and Try",
  8: "Ollwether",
  10: "Domino Effect",
  11: "Sapata",
  12: "Ankels' Camel",
  18: "Katrina SHA",
  19: "Ulusy",
  20: "Whatever"
}

My goal is to have this object sorted in ascending order by value, from A to Z.

I've tried various solutions similar to the one found here

but none of them seem to be working. Regardless of what I try, whenever I convert it to an object, the sorting is based on the key.

Even if I attempt to sort it in the back-end, in JavaScript the object still ends up sorted by ID.

I'm aware that ES6 objects are normally sorted by default.

I've also attempted to use lodash for this task, but unfortunately, without success.

Answer №1

At the outset, it is unclear what server-side error is causing the data to become scrambled. To address this issue, more specific details need to be provided. Additionally, reliance on JavaScript objects may not always yield the desired outcome.

Furthermore, the current approach being taken is neither efficient nor accurate. It is advisable to consider utilizing arrays instead. In the context of Inertia, PHP arrays automatically convert to JavaScript arrays.

However, if by sorting the object you are referring to organizing it as follows:

let result = {
  1: "Abbaga, Sort and Try",
  5: "Ankels' Camel",
  6: "Domino Effect",
  7: "Feearlees",
  8: "Katrina SHA",
  10: "Linga & Satro",
  11: "Ollwether",
  12: "Sapata",
  18: "Ulusy",
  19: "Vexapa",
  20: "Whatever"
}

This can be accomplished in the following manner:

const obj = {
  1: "Vexapa",
  5: "Linga & Satro",
  6: "Feearlees",
  7: "Abbaga, Sort and Try",
  8: "Ollwether",
  10: "Domino Effect",
  11: "Sapata",
  12: "Ankels' Camel",
  18: "Katrina SHA",
  19: "Ulusy",
  20: "Whatever"
};

// Separate keys and values into separate arrays
const keys = Object.keys(obj);
const values = Object.values(obj);

// Sort the keys and values individually
keys.sort((a, b) => Number(a) - Number(b));
values.sort();

// Create a new object by joining the sorted keys and values
const result = {};
keys.forEach((key, index) => {
  result[key] = values[index];
});

console.log(result);

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

Guide to attaching a click event in a subview of Backbone

I'm struggling with understanding event binding in a Backbone subview. Here's how my view is set up: TenantView = Backbone.View.extend({ events: { "click": "setActive" }, initialize: function() { this.parentEl = this.options.parent ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...

Efficiently perform complex nested grouping using the powerful array

Hi, I'm currently facing difficulties while attempting to utilize the array.reduce() function in order to achieve correct grouping for a specific scenario: Here is my original array: { { descriptionFunction: "Change", processDate: "201 ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

Setting a default date dynamically for v-date-picker in the parent component, and then retrieving the updated date from the child component

I'm working with a custom component that utilizes the v-date-picker in various instances. My goal is to have the ability to dynamically set the initial date from the parent component, while also allowing the date to be modified from the child componen ...

The synchronization feature of HighCharts fails to function properly if the charts being used have varying widths

When using HighCharts, I experimented with Synchronized multiple charts following the example in this Fiddle. It worked seamlessly when all the charts had equal width. $('#container').bind('mousemove touchmove touchstart', function (e) ...

ScriptManager.RegisterClientScriptBlock is failing to execute the already existing script

Background When a client-side button click triggers a server-side function, a loading panel (div) is displayed before the server-side function is executed. The loading panel should be removed once the server-side function completes. My Approach Upon com ...

When adding margin-left and margin-right, images do not appear in their designated positions

I have a chart displaying images, which are showing up correctly. However, I am facing an issue when I try to add some spacing to the chart by using margin-left and margin-right. Here is the CSS code I included: #chart1 { margin: 0 auto; ...

Retrieving Blocked Images with Selenium: A Step-by-Step Guide

HTML: <html> <head> <body onload="document.getElementById('a').style.display='block';"> <div id="a" align="center" onclick="document.location.reload();" style="display: block; cursor: pointer;"> <img width="9 ...

How to access v-model value in VueJS methods

Hey there, I am currently using Vuetify for my carousel component and I am looking to customize the duration of each slide in the carousel. This is what my template looks like: <v-carousel cycle :interval="interval" v-model="onSlideChang ...

Steps to display a JSX component stored in a variable

Presently, I am implementing an if/else statement within my code to determine the content that will be displayed in the JSX element named 'signupMessage'. Subsequently, I render the contents of this 'signupMessage' element. render() { ...

Encountering a data retrieval issue when using the useSWR hook in a project using reactjs

I am trying to retrieve data from the backend using useSWR. However, I have encountered two bugs in the function getDataUseSWR. The errors occur at line 'fetch(url).then': 1: "Expected 0 arguments, but got 1."; 2: "Property 'then' does ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Activate the drop-down division when the search box is in focus with xoxco technology

Currently, I am incorporating Xoxco's tag input plugin which can be found at the following link: In my customization, I have implemented JQuery's focus() function <input id="tags_1" class="tag-holder" type="text" class="tags" /></p> ...

Sending a PHP variable to a JavaScript function

When attempting to pass a value to a JavaScript function by clicking a link, I encountered an error message: Uncaught SyntaxError: Unexpected identifier The following is the code snippet: <?php include_once("php_includes/check_login_status.php") ...

Ways to verify whether a user is not defined

My code includes a command that sends a Direct Message to a user, with the user being specified as follows: let user; if (message.mentions.users.first()) { user = message.mentions.users.first(); } else if (args[0]) { user = message. ...

JavaScript PIP video feature

Currently, I am utilizing the requestPictureInPicture function to display the HTML video element in a popup window. However, I have encountered an issue where the size is restricted to approximately 920 x 540 when in Picture-in-Picture mode. I am wonderin ...

Tips for ensuring that the cursor is directed to the initial input when using a Vue template form generator

If you're looking for an example, check out the readme of this page: https://github.com/vue-generators/vue-form-generator My goal is to focus the cursor on the first input field in a Vue form generator, specifically the "Name" field. I've atte ...

What happens when the `.push` command runs the "Undefined" function in jQuery - is it possible to execute a number instead?

My script is quite simple - I'm trying to use the push method to add the result of a function called dNumber into the variable named pattern. However, every time I try this, the result is always "undefined". Oddly enough, when I try pushing just plain ...

Mastering the ng-submit directive for AngularJS

Having an issue with my form that submits a location to Google's Geocoder and updates the map with the lat/long. When using ng-click on the icon, it requires double clicking to work properly. And when using ng-submit on the form, it appends to the URL ...