Order the keys in a JSONArray

My json Array structure is as follows:

[
    {
        "pos1": "Batterie de préchauffage",
        "attributes": [
            {
                "disconnect": "false",
                "disconnectBis": "false"
            }
        ]
    },
    {
        "pos4": "Batterie haute température",
        "attributes": [
            {
                "test": "true",
                "testBis": "false"
            }
        ]
    },
    {
        "pos3": "free"
    },
    {
        "pos2": "free"
    }
]

I am looking to rearrange my json data to achieve the following format:

[
    {
        "pos1": "Batterie de préchauffage",
        "attributes": [
            {
                "disconnect": "false",
                "disconnectBis": "false"
            }
        ]
    },
    {
        "pos2": "Batterie haute température",
        "attributes": [
            {
                "test": "true",
                "testBis": "false"
            }
        ]
    },
    {
        "pos3": "free"
    },
    {
        "pos4": "free"
    }
]

I need to ensure that the 'pos' values are in progressive order.

I hope someone can understand my issue and provide guidance on how I can resolve this problem. I have searched extensively but haven't found a solution specific to my situation.

Thank you for your help!

Answer №1

Arriving a bit fashionably late, it seems the existing answers may not be giving you the desired output. What you're looking for is to maintain the current array order and update the current pos[num] property of the object in the array with 'pos' + (idx + 1):

const input = [ { "pos1": "Batterie de préchauffage", "attributes": [ { "disconnect": "false", "disconnectBis": "false" } ] }, { "pos4": "Batterie haute température", "attributes": [ { "test": "true", "testBis": "false" } ] }, { "pos3": "free" }, { "pos2": "free" } ]

const output = input.map((o, idx) => {
  const id = Object.keys(o).find(id => /^pos/.test(id));
  if (id !== `pos${idx + 1}`) {
    o[`pos${idx + 1}`] = o[id];
    delete o[id];
  }
  return o;
});

console.log(output)

Answer №2

To organize the objects based on their first property, a simple solution like the one below can be used:

var array = [
    {
        "pos1": "Batterie de préchauffage",
        "attributes": [
            {
                "disconnect": "false",
                "disconnectBis": "false"
            }
        ]
    },
    {
        "pos4": "Batterie haute température",
        "attributes": [
            {
                "test": "true",
                "testBis": "false"
            }
        ]
    },
    {
        "pos3": "free"
    },
    {
        "pos2": "free"
    }
];

var sortedArray = array.sort((a, b) => {
    var nameKeyA = Object.keys(a)[0];
    var nameKeyB = Object.keys(b)[0];
    return nameKeyA > nameKeyB;
});

console.log(JSON.stringify(sortedArray));

Answer №3

Utilizing the JavaScript methods and syntax outlined below will yield the desired output:

const json = '[{"pos1":"Batterie de préchauffage","attributes":[{"disconnect":"false","disconnectBis":"false"}]},{"pos4":"Batterie haute température","attributes":[{"test":"true","testBis":"false"}]},{"pos3":"free"},{"pos2":"free"}]';

// Parse the JSON
const arr = JSON.parse(json);

// `map` over the array, grabbing the object and index
const out = arr.map((obj, i) => {

  // Iterate over the keys from each object
  Object.keys(obj).forEach(key => {

    // If a key includes the substring "pos"...
    if (key.includes('pos')) {

      // ...and the new key number doesn't match the current index...
      if (key !== `pos${i + 1}`) {

        // ...copy it to a new key (starting at pos1)...
        obj[`pos${i + 1}`] = obj[key];

        // ...then delete the old key
        delete obj[key];

      }
    }
  });

  // Return the updated object 
  return obj;
});

console.log(out);

Answer №4

If the pattern of names follows pos[num], then this solution will be effective.

let data = [
    {
        "pos1": "Preheating battery",
        "attributes": [
            {
                "disconnect": "false",
                "disconnectBis": "false"
            }
        ]
    },
    {
        "pos4": "High-temperature battery",
        "attributes": [
            {
                "test": "true",
                "testBis": "false"
            }
        ]
    },
    {
        "pos3": "free"
    },
    {
        "pos2": "free"
    }
];

const sortPredicate = (a, b) => {
  
  let aProp = parseInt(Object.getOwnPropertyNames(a)[0].substring(3));
  let bProp = parseInt(Object.getOwnPropertyNames(b)[0].substring(3));

  return  aProp - bProp;
}

let sortedData = data.sort(sortPredicate);

console.log(sortedData);

Answer №5

let arr = [
    {
        "key1": "Value 1",
        "attributes": [
            {
                "flag1": "true",
                "flag2": "false"
            }
        ]
    },
    {
        "key4": "Value 4",
        "attributes": [
            {
                "check": "true",
                "checkBis": "false"
            }
        ]
    },
    {
        "key3": "free"
    },
    {
        "key2": "free"
    }
];

function getKey(obj) {
  const firstMatch = Object.keys(obj).find(k => /key[0-9]+/.test(k));
  return firstMatch;
}

const ordered_keys = arr.map(o => getKey(o)).sort();
arr = arr.map((o, idx) => {
  const k = getKey(o);
  if(k && ordered_keys[idx] && k !== ordered_keys[idx]) {
    o[ordered_keys[idx]] = JSON.parse(JSON.stringify(o[k]));
    delete o[k];
  }
  return o;
});

console.log(JSON.stringify(arr, null, 2));

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

Highchart: precise positioning of ticks on axis

Is there a way to precisely determine the distance or establish an exact distance (in pixels) between two ticks on the x-axis using Highchart? I attempted to use tickPixelInterval, but it doesn't appear to accurately set the distance between two tick ...

Error Encountered When Updating cGridView in Yii: "TypeError: $.fn.yiiGridView is undefined"

I'm encountering an issue with updating the gridview TypeError: $.fn.yiiGridView is undefined; after using AjaxLink Click Button for Refresh <script> $(document).ready(function(){ $("#tombol_refresh").click(function(){ $.fn.yiiGridView ...

What causes my XMLHttpRequest to be terminated prematurely?

My code utilizes an XMLHttpRequest to log in to a remote server by sending login parameters (username and password) as JSON. Here is my code snippet: var json_data = JSON.stringify({ "method": "login", "user_login": user, "password": password ...

Redux accesses the store data after a brief delay

I am new to using redux and I am currently working on implementing it for my very first project. Everything seems to be working fine, however, when I try to console.log the data from the redux store, initially it shows two empty arrays but in the subsequen ...

Bring in 2 Angular applications into a different JavaScript project

In my current setup, I have 2 distinct Angular projects. To build each project, I execute the following CLI command: ng build --prod --output-hashing=none Following this command, the build process generates the below files for each project: runtime.js ...

JavaScript Bingo Game - Create Interactive Cell Selection

Below is the HTML code that I am using to create a Bingo card: ... <th class="orange">B</th> <th class="orange">I</th> <th class="orange">N</th> ...

Mapping a list of objects from my model to a JavaScript variable for populating fullcalendar events

I have been working on retrieving my fullcalendar events in an object array and then storing it in my view model to pass to JavaScript. However, I encountered an error when trying to store it in the scripts section as eventArray! My service layer code... ...

When trying to parse a non-alphanumeric string using Number.parseInt, the resulting type will be 'number'

Here's what is going on: The typeof Number.parseInt('processed') statement returns 'number'. https://i.sstatic.net/1mpaI.png However, when Number.parseInt('processed') results in NaN. https://i.sstatic.net/gVVgV.png ...

Customizing the step function of HTML5 input number with jQuery: A guide

Is there a way to modify the step value in HTML5 number inputs for my web application? I would like it to increment and decrement by 100 instead of 1. I attempted the following approach: $("#mynumberinput").keydown(function(e){ if (e.keyCode == 38) / ...

How can I retrieve the identical fingerprint used by AWS from x.509 using node-forge?

Is there a way to obtain the certificate ID / fingerprint of an x.509 certificate using the node-forge library? Update I am trying to configure AWS IoT and believe that AWS uses a specific fingerprint algorithm to generate the certificate ID. This inform ...

The value of the variable remains consistent throughout the .each function when using JQuery's .post() method

I am facing a dilemma with a variable value discrepancy within the $.post function compared to the parent function $(element).each(function. Below is the snippet of my code: $(document).ready(function() { $(".list").each(function() { var a = $(thi ...

Loop through the JSON array and append every value to the list within AngularJS

I'm just starting to learn about Angular JS and I have a question. I receive a JSON array as an AJAX response from a PHP page. I want to iterate through this JSON array and push each value into a list like this: angular.forEach($scope.companies.area, ...

In Typescript, what is a function that can return multiple types separated by commas known as?

As someone who is new to Typescript, I recently came across the following syntax: interface Foo { // what does age signify and // what if it is not optional i.e () => string, age:number; (): () => string, age?: number; } From what I ...

What is the best way to transform a nested EJS foreach loop into a HBS foreach loop?

After switching from EJS to HBS for my project, I need help translating my EJS code to HBS syntax. Here is a snippet of my EJS code, but I'm struggling with understanding the syntax in HBS: <% projeler.forEach(proje_dizisi=> { %> <% pro ...

What could be the reason for my post jQuery Ajax request sending JSON data?

After downloading some code, I came across the following fragment: function FetchCommentsBySessionIDWCF_JSON() { varType = "POST"; varUrl = "service/CommentSessionIDWCFService.svc/FetchCommentsByPost"; varData = ' ...

Is there a way to align a button in the center of the browser's footer?

Removing these two elements will enable the image to display properly, however, it does not stay aligned with the footer when viewed in a browser. Here is a preview of how it looks: Below is the CSS code along with the HTML: <style> body { ...

Ionic 2: Inconsistency detected in the expression after it was verified

After going through this response, this solution and this advice (as well as numerous others), I still find myself struggling to comprehend how to resolve this issue in my current approach. The task at hand involves creating an event countdown timer that ...

Must run the angular code in a sequential order

I need to run the code in a specific order; first the foreach loop should be executed, followed by a call to the getHistory() method. Your assistance is greatly appreciated. const execute = async()=>{ await this.currentContent.forEach(async ...

Retrieving input data when utilizing ng-file-upload

I need help with uploading images and their titles using ng-file-upload in the MEAN stack. I am able to save the image successfully, however, I'm facing difficulty in retrieving the data sent along with it. Controller: module.exports = function ($sc ...

Extracting and retrieving the value from the paramMap in Angular/JavaScript

How can we extract only the value from the router param map? Currently, the output is: authkey:af408c30-d212-4efe-933d-54606709fa32 I am interested in obtaining just the random "af408c30-d212-4efe-933d-54606709fa32" without the key "authke ...