Order JSON data based on a predetermined list of keys using JavaScript

Imagine having a JSON list called LIST A:

LIST A

[
  {
    "address": "wellington lane",
    "age": "23",
    "country": "Australia",
    "name": "Mike",
    "profession": "Lawyer"
  },
  {
    "address": "Street 25",
    "age": "26",
    "country": "New Zealand",
    "name": "Parks",
    "profession": "Engineer"
  },
  {
    "address": "North cross",
    "age": "29",
    "country": "Korea",
    "name": "Wanda",
    "profession": "Doctor"
  }
]

LIST B

["name","age","address","country","profession"]

The task is to sort the JSON LIST A based on the array LIST B, resulting in:

[
  {
    "name": "Mike",
    "age": "23",
    "address": "wellington lane",
    "country": "Australia",
    "profession": "Lawyer"
  },
  {
    "name": "Parks",
    "age": "26",
    "address": "Street 25",
    "country": "New Zealand",
    "profession": "Engineer"
  },
  {
    "name": "Wanda",
    "age": "29",
    "address": "North cross",
    "country": "Korea",
    "profession": "Doctor"
  }
]

How can this be achieved? I attempted this approach but it did not work as expected.

Answer №1

Hello there, one possible approach is to iterate through both arrays and construct a new array with ordered attributes. Here's a sample code snippet to achieve this:

let data = [
      {
        "address": "wellington lane",
        "age": "23",
        "country": "Australia",
        "name": "Mike",
        "profession": "Lawyer"
      },
      {
        "address": "Street 25",
        "age": "26",
        "country": "New Zealand",
        "name": "Parks",
        "profession": "Engineer"
      },
      {
        "address": "North cross",
        "age": "29",
        "country": "Korea",
        "name": "Wanda",
        "profession": "Doctor"
      }
    ]

    let attributes = ["name","age","address","country","profession"]
    
    let result = [];
    
    data.forEach(element => {
       let resultObject = {}
       attributes.forEach(attribute => {
          resultObject[attribute] = element[attribute]          
       })
       result.push(resultObject)
    })
    
    console.log(result)

Answer №2

Check out this innovative approach utilizing map and reduce:

const data = [
  {
    "name": "Mike",
    "age": "23",
    "address": "wellington lane",
    "country": "Australia",
    "profession": "Lawyer"
  },
  {
    "name": "Parks",
    "age": "26",
    "address": "Street 25",
    "country": "New Zealand",
    "profession": "Engineer"
  },
  {
    "name": "Wanda",
    "age": "29",
    "address": "North cross",
    "country": "Korea",
    "profession": "Doctor"
  }
];

const order = ["name", "age", "address", "country", "profession"];

const orderedData = data.map(item => order.reduce((acc, key) => ({ ...acc, [key]: item[key] }), {}));

console.log(orderedData);

Answer №3

Here is a method to achieve this task without the need for an external library:

const arr = [
  {
    'address': 'wellington lane',
    'age': '23',
    'country': 'Australia',
    'name': 'Mike',
    'profession': 'Lawyer',
  },
  {
    'address': 'Street 25',
    'age': '26',
    'country': 'New Zealand',
    'name': 'Parks',
    'profession': 'Engineer',
  },
  {
    'address': 'North cross',
    'age': '29',
    'country': 'Korea',
    'name': 'Wanda',
    'profession': 'Doctor',
  },
];
const keyOrder = ['name', 'age', 'address', 'country', 'profession'];

function applyKeyOrder(obj, keyOrder) {
  const res = {};
  for (const key of keyOrder) {
    res[key] = obj[key];
  }
  return res;
}

const result = arr.map(element => applyKeyOrder(element, keyOrder));
console.log(result);

It is important to note that this method assumes that all keys in the keyOrder array exist in the objects. Any fields not present in the array would be omitted in the final result.

Answer №4

When referencing "SECTION X" as sectionX and "SECTION Y" as sectionY:

const organizeSections = () => {
    return sectionX.map(sectionItem => {
        const result = {};
        sectionY.map(itemLabel => {
            result[itemLabel] = sectionItem[itemLabel];
        })
        return result;
    })
};

console.log(organizeSections())

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

Learn how to move a div inside another div using drag and drop, ensuring that the entire element moves along with it

I am trying to implement jQueryUI for my project. I have a list of components that I want to drag and drop into a grid system, similar to a designer tool. I am using the following code to make the div draggable: $( "#Component1" ).draggable(); Then I dro ...

Ways to create an angularJS $watch function that is able to recognize modifications in styling

I have a rich text box equipped with all the necessary style controls. If I input new text, it saves without any issue. Whenever I modify the content (text) and add styles like color highlighting or bold formatting, the changes are saved successfully. H ...

Setting the Date in Angular.js: A Step-by-Step Guide

Make maxDate selectable as today at the latest (past days are clickable but not tomorrow). The range between minDay and maxDay should not exceed 365 days, allowing for fewer days to be selected. $scope.dateOptions = { formatYear: " ...

Using AJAX to assign PHP session variables

Is there a way to update the SESSION variable named "fullname" on Page 2 without causing the page to refresh? This is my attempt using AJAX: HTML code for Page 1: <input type="text" name="fullname" id="fullname" placeholder="Full name"> <butto ...

What is the method to show text on hover in angularjs?

I'm a beginner in AngularJS and I'm looking to show {{Project.inrtcvalue}} when the mouse hovers over values. Can anyone guide me on how to achieve this using AngularJS? <table ng-table="tableParams" show-filter="true" class="table" > ...

Another option for authorizing a document

DISCLAIMER: I am seeking information on technologies for signing a JSON document from the server-side, not recommendations for specific products or services. I want to explore the various options available for signing a JSON document, especially when mult ...

The sub-menu is being obscured by a PDF element in Internet Explorer, causing visibility issues

I have an object type tag on my page that displays a PDF file. Everything is functioning correctly, but in Internet Explorer, my sub-menu is being hidden behind the object tag. var objTag = $('<object></object>') .attr({ data: source ...

Google Maps Circle Radius Functionality Malfunctioning

I've been trying to implement a map scaling feature using a slider in my code but I'm having trouble getting it to work. While the map is displaying correctly, the radius won't update as intended. Any assistance with this would be greatly ap ...

Unlocking the Potential of Checkbox Values in AngularJS

I am attempting to extract data from a $rootScope object that has been linked to the checkboxes. HTML: <tr ng-repeat="system_history in SystemHistoryResponse.system_history"> <td><input type="checkbox" ng-model="versionValues[system_histor ...

Automatically select all options in MUI Autocomplete by default

Is there a way to have all the values in the autocomplete drop down automatically selected by default when the page loads? I've been experimenting with this example but haven't found a solution yet. If you know how to achieve this, please share! ...

Issues stemming from cross-domain AJAX have resulted in errors with Karma and Jasmine

I've been working on configuring tests that utilize Jasmine and Karma to test my JavaScript code. Karma operates in Node.js and initiates a Chrome browser for testing purposes. Unfortunately, I keep encountering an error message that reads "Chrome 28 ...

Obtaining information from a local JSON file in AngularJS

I'm facing some issues with retrieving data from a JSON file using the structure below. In my controller.js file, I've written: var controllers = angular.module('hotels.controllers', []); controllers.controller('AppCtrl', f ...

How to Retrieve Upload Progress via HTTP Request in PHP

Is there a way to monitor the progress of file uploads by accessing the HTTP request in PHP? If so, how can this be achieved when uploading files into a MySQL database? require('../connect_db.php'); //Collect all necessary data $name = $dbc-> ...

Creating a function in JavaScript to return an Unsubscribe and Array from a Firebase Snapshot Listener in Svelte

In my SvelteKit project, I have integrated Firebase Firestore. I maintain a db.js file that contains various functions utilized in Svelte components. One such function is detailed below. export const Items = { async getMany() { let dbRef = db.c ...

Please provide values in the input box, with each value separated by

I attempted the following code: success: function (result) { for (var i = 0; i < result.d.length; i++) { var emails = new Array(); emails = result.d[i].Emailid; alert(emails); $("#EmailCC").val(emails); ...

What is the best way to reset the state to null when the input field is blank?

After setting some inputs with a state of null, I noticed that when the end-user types something and then deletes it all, the input reverts back to an empty string. How can I adjust the state so that it returns to null? I seem to be encountering an issue ...

How can I pull the account creation date stored in MongoDB and display it using Handlebars?

Currently in my development, I am utilizing MongoDB, NodeJS, and Handlebars. My challenge is to convert the user.id into a timestamp and then display this timestamp on my HTML page. At present, I can display the user.id by using {{ user.id }} in my code, ...

Refresh a function following modifications to an array (such as exchanging values)

Looking to re-render a function after swapping array values, but the useEffect hook is not triggering it. I need assistance with this as I plan to integrate this code into my main project. Below are the JSX and CSS files attached. In App.js, I am creating ...

Utilizing Ajax to dynamically generate unique ID's for multiple checkboxes

I have been working on a website that is almost completed, however, I have come across a new task where I need to select check-boxes in order to archive news items or "blog posts". The concept is to have a check-box next to each blog post and by checking ...

Toggle switch with active state

I'm currently using Ionic 2 alongside Angular 2 beta 11. Is there a way to turn off the toggle switch? The Ionic documentation suggests using the checked attribute, but I've tried that and also attempted ng-checked with no luck. Any advice on t ...