What is the best way to arrange the keys of a JavaScript object in a customized

I am struggling to find a way to custom sort a JavaScript object properly. For example, I have the following object:

var test = {
  'yellow': [],
  'green': [],
  'red': [],
  'blue': []
}

And an array with values like:

var arr = ['red', 'green', 'blue', 'yellow'];

My goal is to sort the object based on the order specified in the array:

var test = {
  'red': [],
  'green': [],
  'blue': [],
  'yellow': []
}

However, my current sorting attempts are not giving me the desired result. The loop and sort method I'm using seems to be sorting alphabetically instead of following the order of the array. I've tried using the keys of the object but it's still not working as expected:

var test = {
  'yellow': [],
  'green': [],
  'red': [],
  'blue': []
}

var keys = Object.keys(test);

console.log(keys.sort()); //["blue", "green", "red", "yellow"] which is not the intended order or format

I need some guidance on how to achieve this custom sorting based on a specific order. Additionally, I have a requirement to use Handlebars for templating, and I want to maintain the order when looping through the objects. Is there a proper way to handle this within Handlebars without losing the benefits of the template engine?

Answer №1

If you want to change the order of keys in a JSON object, you can use JSON.stringify(). Here's how:

Follow these steps:

var json = {     "name": "David",     "age" : 78,     "NoOfVisits" : 4   };
console.log(json);
//outputs - Object {name: "David", age: 78, NoOfVisits: 4}
//change order to NoOfVisits,age,name

var k = JSON.parse(JSON.stringify( json, ["NoOfVisits","age","name"] , 4));
console.log(k);
//outputs - Object {NoOfVisits: 4, age: 78, name: "David"} 

Create an array with the key order you want and pass it to the function. Then, parse the result back to JSON format.

Answer №2

When it comes to JavaScript objects, they are essentially unordered due to their hash-like nature. This means that the order in which properties are listed cannot be controlled. Any apparent ordering when keys are enumerated is merely coincidental and should be seen as a specific detail of how the JavaScript engine operates.

To achieve a desired order, you would need to use an array of objects instead.

In summary, the data structure you have selected does not support maintaining a specific order of properties.

Answer №3

You may want to consider utilizing the Map() function

A Map object cycles through its elements in the order they were inserted

var colors = ['red', 'green', 'blue', 'yellow'];

var colorMap = new Map();

colors.forEach(function(value, index) {
  var obj = {};
  obj[value] = [];
  colorMap.set(index, obj)
});

console.log(colorMap)

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

Tips for validating date input in a TextBox using JQuery on an ASP.NET platform:

Here is some code I wrote: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="datetime.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <tit ...

Implementing dual language codes for a single locale in internationalization (i18n) efforts

I am currently using i18n to display translations in English and Japanese. The default language is set to English with the code en, but I have recently discovered that my website is not utilizing the correct ISO language code for Japanese, which should be ...

A node module designed to efficiently convert multiple TIFF images into a single multipage TIFF document

Looking to combine several tiff images into a single file using nodejs/javascript. Is there a method to create a single tiff file with multiple pages from separate tiff images in nodejs? Can we convert a multi-page pdf into one tiff image using nodejs? ...

Real-time functionality is not supported by Firebase functions

I've set up a firebase query within a method in VueJS: data: {this.todaysEvents}, methods : { getTodaysEvents (day) { this.todaysEvents = [] const events = db.ref('calendar') const query = events.orderByChild('da ...

Stubborn boolean logic that refuses to work together

Seeking guidance on resolving a persistent issue with my website that has been causing me headaches for the past few weeks. This website was created as my capstone project during a recent graduate program, where I unfortunately did not achieve all the desi ...

Eliminate redundant XML entries when using jQuery autocomplete

Does anyone know how to prevent duplicate records from appearing in a jQuery autocomplete dropdown? I am pulling data from an XML file and want to ensure that each record is unique and only displayed once. You can see the issue here ...

What steps can I take to resolve the Angular JS error message: [$injector:unpr]?

index.html <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="UTF-8"> <title>Angular JS</title> <script src="lib/angular.min.js"></script> ...

Adjust Mui Autocomplete value selection in real-time

I have implemented Mui AutoComplete as a select option in my Formik Form. <Autocomplete disablePortal options={vendors} getOptionLabel={(option) => option.vendor_company} onChange={(e, value) => {setFieldValue("vendor_id", value. ...

Please enter a numerical value into the input field in a JavaScript form

<script> function loop() { var input = document.getElementById('inputId').value; for (var i = 0; i < input; i++) { var result = document.getElementById('outputDiv').innerHTML ...

Trigger JavaScript when a specific division is loaded within a Rails 4 application

Is there a way to trigger a JavaScript function when a specific div with a certain class is loaded within my Rails 4 application? <div class="myClass"> hello world </div I am looking for a solution to execute some JavaScript code only when t ...

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...

Issue: The value of an object is not defined (evaluating '$scope.inputcode.password')

HTML Form: <form ng-submit="mylogin()"> <div class="list"> <label class="item item-input"> <span class="input-label">Username</span> <input type="text" ng-model="inputcode.username"> ...

Pace.js doesn't bother waiting for iframes to completely load before moving on

On my website, I am using pace.js but encountering issues with pages containing iframes. Is there a method to ensure that pace.js considers the content loading within those iframes? I attempted to configure paceOptions to wait for the iframe selector to l ...

Can you provide me with the URL for the jQuery post function?

Could someone please clarify which URL I should use in the $.post call to the server for a node.js file? Most tutorials demonstrate with PHP files, but I'm unsure about calling node.js files. Should I post it to the app.js file or the route file? Thi ...

Tips for maintaining the current route in Vue.js after a page refresh while running the Vue.js project in development mode on a specific port?

In my router.ts file, I have defined two routes: export default new Router({ mode: "history", routes: [ { path: "/", component: require("./components/dashboard/Dashboard.vue")}, { path: "/counter", component: require("./components/ ...

unable to display loading image prior to upload

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="en"> <head> <title>Unique Prints</title> <meta charset="utf-8"> <meta name="viewport" conte ...

What is the best way to include a new user in the memory database when there is no database or storage back-end?

During an online test, I was given the task of adding a user to a database stored in memory. The request body required JSON formatting as shown below: { "id": "aabbbccddeeefff", "name": "User One", "hobbies": [ "swim", "sing", "workout" ] } (Users ...

Struggling to create a line break within an SVG using the <tspan> element?

I have a pair of text lines that are wrapped in <tspan> tags. <tspan dy="-11.7890625">welcome</tspan> <tspan dy="16.8" x="285.75">text</tspan> I am trying to add a line break between them, but the <br> tag is not worki ...

Assign the private members of the class to the arguments of the constructor

class Bar { #one #two #three #four #five #six #seven #eight #nine #ten #eleven #twelve #thirteen #fourteen #fifteen #sixteen constructor( one, two, three, four, five, six, seven, eight, ...

Relocating scripts that have already been loaded

When using AJAX to load a page, the entire content including <html>, <head>, <body> is loaded. This means that all scripts meant to run on page load will be called. However, sometimes the browser may remember that certain scripts have alr ...