How can JSON attribute/value pairs be rearranged using JavaScript?

Looking at the JSON data below:

[
    { 'Album': 'Dearest', 'Artist': 'Theresa Fu', 'Year': '2009'},
    { 'Album': 'To be Free', 'Artist': 'Arashi', 'Year': '2010'}
]

I am interested in re-ordering the attribute / value pairs using JavaScript on the client side. For example:

[
    { 'Album': 'Dearest', 'Year': '2009', 'Artist': 'Theresa Fu'},
    { 'Album': 'To be Free', 'Year': '2010' 'Artist': 'Arashi'}
]

Is there a straightforward way to achieve this? Or do I need to manipulate strings with JavaScript and then reconstruct the data (any code samples would be helpful). Just so you know, I will only be working with a small amount of data - around 5 attributes and 10-15 rows.

Why am I doing this, you might wonder? Well, my aim is to utilize a JQuery Table plug-in:

As far as I understand, the column order in the grid needs to match the order of attribute/value pairs in the JSON (I'll verify this)... but I want to display them in a different order than they are stored in the payload.

Update... I made a mistake. The plug-in does not require the columns to be in a specific order. I should have tested it before posting instead of assuming. My apologies.

Answer №1

"Update: What is prompting this decision? My intention is to incorporate the JQuery Table plug-in found here:

Based on my understanding, the sequence in which the columns appear in the grid should mirror the arrangement of attribute/value pairs within the JSON"

I'm not familiar with that particular plugin, but according to its demo, the order of columns is determined by the array of objects you input.

columns: [
        { name: 'Album', display: 'Album', type: 'text', ctrlAttr: { maxlength: 100 }, ctrlCss: { width: '160px'} },
        { name: 'Artist', display: 'Artist', type: 'text', ctrlAttr: { maxlength: 100 }, ctrlCss: { width: '100px'} },
        { name: 'Year', display: 'Year', type: 'text', ctrlAttr: { maxlength: 4 }, ctrlCss: { width: '40px'} },
        { name: 'Origin', display: 'Origin', type: 'select', ctrlOptions: { 0: '{Choose}', 1: 'Hong Kong', 2: 'Taiwan', 3: 'Japan', 4: 'Korea', 5: 'US', 6: 'Others'} },
        { name: 'Poster', display: 'With Poster?', type: 'checkbox' },
        { name: 'Price', display: 'Price', type: 'text', ctrlAttr: { maxlength: 10 }, ctrlCss: { width: '50px', 'text-align': 'right' }, value: 0 },
        { name: 'RecordId', type: 'hidden', value: 0 }
    ]

As shown above, the columns attribute consists of objects defining each column.

Since it's an Array, the order is clearly defined. Each object specifies the attributes of a column, so the first one will be labeled as Album, the second as Artist, and so forth.

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

How to use Handlebars in Node.js to parse JSON data

When using Form API in node.js, I encountered JSON data that needs to be parsed. As a beginner, I am unsure how to handle this JSON data properly. [ { "Detail": " Rs. 1001 Full Talktime Topup Rs.1001 Full Talktime", "Amount": "1001", "Validity" ...

Problems with radio button serialization in jQuery form plugin

I've created a basic form: <form class="dataform" method="post" id="settings" action="/"> <input type="radio" name="shareSetting" value="n"/> <input type="radio" name="shareSetting" value="y"/> <input type="button" na ...

problems encountered when including next.config.js for sitemap creation in a nextjs application

Just recently, I made an update to my next.config.json file in hopes of boosting SEO performance. However, this change has caused some issues with the next-sitemap module, preventing me from building or starting my app. //next.config.js const withSitemap = ...

Creating dynamic input forms in PHP

New to PHP and seeking guidance! I'm in the process of creating a photography website and encountering an issue with a specific page. Essentially, I need this page to display a form with a varying number of inputs. The goal is to have a dynamic visua ...

What is the reason for not allowing return statements in the ternary operator?

Imagine you have a basic form and you want to determine if the form has been modified. If it has changed, you want to submit it; otherwise, you want to prevent form submission. To tackle this, instead of using an if-else statement, I decided to go for a te ...

What is the best way to retrieve system information from a properties file and display it on a JSP page before the Javascript code is

As someone who is relatively new to JSPs and their capabilities, I am currently working on developing a suite of 4 separate webapp dashboards, each with its own standalone URL and index.(jsp|html) pages. The backend of these dashboards, which is written in ...

I am looking to dynamically add and remove an active link on my sidebar using JavaScript

Looking to create a dynamic website with interactive features like adding and removing active links upon clicking, and smooth transitioning between sections using JavaScript. Feel free to skip over the SVG code. HTML source code <div class="s ...

Azure ARM: Eliminating unacceptable characters

Does anyone know of a simpler method to remove all non-alphanumeric characters from a string in order to prevent users from inputting invalid characters? Currently, my code involves creating multiple variables to replace each unwanted character individual ...

Deactivate wheel event in jQuery

I am facing a challenge in designing my website using skrollr.js and fullpage.js libraries. Skrollr relies on the value of scrollTop to transform selected elements, while fullpage.js changes the top value of the viewport when scrolling, causing issues with ...

What is a sleek method for including a key and value pair to an object using an array?

In a project using angular2/typescript, I am working with an array of objects that contain key/value pairs from a database. These values are then displayed in a table on the UI using ag-grid-ng2. The table headers are dynamic and set in the database. One ...

The characteristics that define an object as a writable stream in nodejs

Lately, I've been delving into the world of express and mongoose with nodejs. Interestingly, I have stumbled upon some functionality that seems to work in unexpected ways. In my exploration, I noticed that when I create an aggregation query in mongoos ...

Converting CSS code into JavaScript

I am currently working with the following code: .mr15 > * margin-right: 15px &:last-child margin-right: 0 I need help translating this code to Javascript. Should I use JQuery or pure Javascript for this scenario? Thank you. ...

Updating the state using ui-router

The application consists of pages labeled as X, Y, and Z. The intended route is to navigate from page X to select details, then move onto page Y to select additional details, and finally land on page Z. I wish that upon clicking the window's back butt ...

Is there a way to split each foreach value into distinct variables?

I am looking to assign different variables to foreach values. I have fetched data from an API in JSON format, and then echoed those values using a foreach loop. My goal is to display the echoed value in an input box using JavaScript. I attempted the follow ...

AngularJS does not hide the Onsen UI modal

I am new to working with angularjs and onsen ui. I have implemented a modal in an ajax request, which is supposed to hide upon successful response. Everything seems to be working fine, except for the fact that when I navigate back to the page, the modal re ...

Verifying if every item in an array exists within multiple arrays

I am struggling to find a solution to this problem. Imagine there are 6 sets of colors with varying amounts of colors in each, and colors may be repeated: ['white', 'blue'] ['green', 'yellow'] ['black'] [ ...

Validating classes in Node.js using class-validator

I'm having some trouble with the class-validator package in my Node project. It's not being recognized and throwing an error. @MinLength(10, { ^ SyntaxError: Invalid or unexpected token Here's an example of what I'm doing: co ...

Error: Attempting to access an undefined property ('useParams') which cannot be read

Hey there, I'm currently facing some challenges with the new react-router-dom v6. As I am still in the learning phase of this latest version, I could really use some assistance. import React from 'react' function Bookingscrren({match}) { ...

Testing Your Angular 7 Code: Unit Testing Made Easy

I am currently working on developing unit tests for this angular script: export class DataService { private csrfToken: string = ''; private isContentShown: BehaviorSubject<boolean> = new BehaviorSubject(true); constructor(private h ...

Unable to retrieve data from my json file in React

I have successfully created a menu with a submenu and a third child element. Initially, I had hard-coded the data in a local constant called json, which is now commented out. However, I am facing an issue as I now need to fetch the data from my JSON file b ...