Tips for Rearranging Columns in an Array of Objects

I have an array of objects that I need to rearrange the columns and add a static value to each one:

 var homes = [
        {
            "h_id": "3",
            "city": "Dallas",
            "state": "TX",
            "zip": "75201",
            "price": "162500"

        }, {
            "h_id": "4",
            "city": "Bevery Hills",
            "state": "CA",
            "zip": "90210",
            "price": "319250"
        },...
    ];

The desired format is as follows:

 var homes = [
        {
            "h_id": "3",
            "price": "162500",
            "zip": "75201",
            "city": "Dallas",
            "state": "TX",
            "staticValue":  "1234"
        }, {
            "h_id": "4",
            "price": "319250",
            "zip": "90210",
            "city": "Bevery Hills",
            "state": "CA",
            "staticValue":  "1234"
        },...
    ];

I have attempted this approach:

let data = homes.map(function(x) {
                                  return {h_id:x.h_id,
                                         price : x.price,
                                         zip : x.zip,
                                         city : x.city,
                                         state : x.state,
                                         staticValue : "1234"}
                                   });

However, the column order remains the same:

h_id,city,state,zip,price,staticValue

Instead of the desired order:

h_id,price,zip,city,state,staticValue

What could be causing this issue?

Edit

In reality, I am using this reordering method to send the object as a DataTable to a C# controller. Upon reaching the Controller, the ordering is correct. It seems that the map function used has functioned properly.

Here's a working example: jsfiddle.net/a6o8jbh9/1

Answer №1

It is not possible to perform that action

An object represents an unordered collection of name/value pairs

If maintaining order is crucial, consider using arrays instead of objects.

The sequencing of object properties is non-standard in ECMAScript as well.

I am unsure why there is a need to rearrange the objects; they can be easily accessed by their property names. What benefits are expected from reordering?

Since the introduction of ES2015, methods have been implemented following specific guidelines for determining property order, with rare exceptions where order is chronological. Object property order relies on the type of properties and their values. Thus, order can be guaranteed.

A demonstration can be made with the use of the map function

var homes = [
        {
        "1abc": "162500",
            "h_id": "3",
            "city": "Dallas",
            "state": "TX",
            "zip": "75201"


        }, {
            "h_id": "4",
            "city": "Bevery Hills",
            "state": "CA",
            "zip": "90210",
            "1abc": "319250"
        }
    ];
let data = homes.map(function(x) {
                                  return {h_id:x.h_id,
                                         '1abc':x["1abc"],
                                         zip : x.zip,
                                         city : x.city,
                                         state : x.state,
                                         staticValue : "1234"}
                                   });
console.log(homes)

console.log(data)

The resulting output will appear like this

https://i.sstatic.net/Ar0Ln.png

https://i.sstatic.net/O1ATW.png

In the output, the order has changed. Following ES2015 standards, property order adheres to specific rules, thus reorder accuracy cannot always be ensured. It may work in some scenarios (if input matches defined rules), but not all cases.

Note: Considering your comment, it seems you require sending this object to a controller action to then execute a merge query. In such a case, the Json object's order should not impact operations. Your c# model binder possesses the ability to bind correctly with the controller object. If your controller logic is correct and interacts with the SP appropriately, adjusting Json property order would not resolve any issues.

Answer №2

It is essential to correctly access the properties and rearrange them in the right order - ES6 offers valuable functionalities for achieving this:

const updatedData = homes.map(({ h_id, city, state, zip, price }) => ({ h_id, price, zip, city, state, staticValue: "1234" }));

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

The use of conditional statements in AngularJS, such as if-else statements

Recently, I've been experimenting with some AngularJS code and encountered a minor challenge that I need assistance with. My goal is to allow users to choose from three different options. Below is the HTML snippet for this: <label class="item item ...

Having difficulty populating a selection box through an ajax request in Django

I am facing an issue with creating cascading select boxes in my project (backend Django), although I believe most of the backend work has been completed. The JavaScript code I'm using is adapted from a solution found on a stackoverflow post. $(docume ...

Using AJAX to submit a PHP form without refreshing the page

Currently, I am facing an issue with my PHP and AJAX code for posting data without redirecting the page. Surprisingly, the script works perfectly on the login page but not on other pages. The main difference I observed is that the login page uses if (empty ...

How can I efficiently pass a JavaScript object to a function using jQuery syntax?

Recently, I've delved into the world of JavaScript and started exploring object orientation, prototyping, and using objects for all functions and variables. However, there is one aspect that many frameworks like jQuery or extJS have that I struggle wi ...

Displaying two arrays using ng-repeat leads to an error

In my attempt to create a table using two arrays in AngularJS, one containing Employees' names and the other containing Services' names, I encountered an error: Error: [ngRepeat:dupes] Below is my AngularJS code: var model = angular.modul ...

What is the best way to refresh updated .js files directly from the browser console?

Is it possible to use RequireJS 2 to dynamically reload a recently updated .js file? Let me explain my scenario: I have a Backbone.js object named Foo with a function called Bar that currently displays an alert with "abc" when called; In my webpage, I ex ...

I am looking to eliminate any special characters from a designated section of a string using Javascript

I have a string that looks like this: var myString = '{"key1":"value1", "key2":"value2", "key3":"value3"}'; My objective is to remove double quotes and other special characters only from value3. Sometimes the string may look like: var myStrin ...

What are some effective methods for comparing two extremely large arrays in Ruby?

I'm facing an efficiency and algorithm challenge in finding the disparity between two extensive arrays. If anyone well-versed in algorithms could steer me towards a solution, I would greatly appreciate it as my current approach is proving to be excess ...

Exploring the Differences in Site Navigation: PHP/HTML, Ajax, and CSS/Javascript

Lately, I've been weighing the pros and cons of using AJAX for my website navigation to transfer only necessary updated HTML elements. Alternatively, if there isn't a significant difference between new elements and current ones, just loading the ...

What is the correct way to execute a jQuery trigger on a checkbox or radio button to simulate a user clicking on it?

My current page utilizes can.js, making it challenging to replicate the issue on jsfiddle.net. The result I am experiencing is as follows: When I click on a checkbox (or even a radio button), an input text box should update accordingly (for example, displ ...

React and Axios: Overcoming CORS Policy to Connect with Java/SpringBoot REST Backend Service

As a first-time user of Axios to connect to my Java/SpringBoot Rest GET service on localhost:8080, I am using React and node.js. My goal is to successfully retrieve the REST data but encountered the following error: Failed to compile src\App.js Lin ...

Exploring the depths of Master-Detail functionality with Ionic and Angular, unlocking nested

Hey there! I'm currently working on a project using Ionic and Angular, where users can view events and see all the attending participants along with their information. To achieve this, I implemented a master-detail pattern within another master-detail ...

What is the best way to determine the length of an array using input from an HTML form?

Currently, I am in the process of developing a PHP file and one feature that I would like to implement is creating an array as illustrated in Example 1. As far as my understanding goes, an Array functions like a list where items can be added as shown in Ex ...

Updating view model data in Knockout from a different view model can be achieved by using observable properties and

For my web page, I am utilizing Knockout.js to connect various sections together. Each section is associated with its own view model data. When a change is made to an element in one view model, I need to automatically update a corresponding element in an ...

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

What is the best way to store the JSON data that is returned in a JavaScript function as a variable

My goal is to save the client's IP address in a variable after fetching it in JSON format from api.ipify.org. I have managed to display the IP if I alert the result, but I am struggling to store it in a variable. This code snippet works: <script& ...

Switch up your code and toggle a class on or off for all elements that share a specific class

I've been attempting to create a functionality where, upon clicking a switch, a specific class gets added to every element that is assigned the class "ChangeColors". Unfortunately, I have encountered some difficulties in achieving this task. The error ...

Ensure Website Accessibility by Implementing Minimum Resolution Requirements

Is it possible to create a website that only opens on screens with a resolution of at least 1024 x 768, and displays an error message on unsupported resolutions? I've tried using JavaScript to achieve this, but haven't had any success. Any assis ...

Exploring the depths of Vue.js: Maximizing potential with nested

In my Grid component, I retrieve JSON data from a server and render it. The data mainly consists of strings and integers, but sometimes includes HTML elements like <strong>myvalue</stong>. In order to properly display the data, I use triple bra ...

The definition of Csrftoken is missing

The code I am currently using, as per the recommended documentation, is: function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); ...