Sorting an array of objects keys according to the position of keys in another array

I have two arrays: one with the correct order of keys and values, and another array coming from a backend in an unsorted format.

let arr1 = ['name', 'age', 'occupation', 'address']
let arr2 = [{'age': 20, 'address': '', 'occupation': 'student', 'name': 'student name1'}, {'age': 21, 'address': '', 'occupation': 'student', 'name': 'student name2'}, {'age': 22, 'address': '', 'occupation': 'student', 'name': 'student name3'}]

The goal is to sort the keys of the second array based on the order of keys in the first array.

Desired final output:

let arr2Sorted = [{ 'name': 'student name1', 'age': 20, 'occupation': 'student', 'address': ''}, { 'name': 'student name2', 'age': 21, 'occupation': 'student', 'address': ''}, { 'name': 'student name3', 'age': 22, 'occupation': 'student', 'address': ''}]

This is how I attempted to achieve it:

const arrayMap = arr2.reduce(
      (accumulator, currentValue) => ({
         ...accumulator,
         [currentValue]: currentValue,
      }),
     {},
    );

const result = arr1.map((key) => arrayMap[key]);

Answer №1

const dataKeys = ['name', 'age', 'occupation', 'address'];
const dataObjects = [{'age': 20, 'address': '', 'occupation': 'student', 'name': 'student name1'}, {'age': 21, 'address': '', 'occupation': 'student', 'name': 'student name2'}, {'age': 22, 'address': '', 'occupation': 'student', 'name': 'student name3'}];

let result = dataObjects.map(item => Object.fromEntries(dataKeys.map(key => [key, item[key]])));

console.log(result);

Answer №2

Explaining why there is no need to order properties, just utilize them effectively. Detailed "How To" explanation included.

const dataArr = ['name', 'age', 'occupation', 'address'];
const objArr = [{
  'age': 20,
  'address': '',
  'occupation': 'student',
  'name': 'student name1'
}, {
  'age': 21,
  'address': '',
  'occupation': 'student',
  'name': 'student name2'
}, {
  'age': 22,
  'address': '',
  'occupation': 'student',
  'name': 'student name3'
}];
// demonstrating the use of props without ordering
const displayContainer = document.getElementById("container");
objArr.forEach((element) => {
  dataArr.forEach((propName) => {
    const textNode = document.createTextNode(propName + ":" + element[propName]);
    let divElement = document.createElement('div');
    divElement.appendChild(textNode);
    displayContainer.appendChild(divElement);
  });
});

// showcasing different ways to order props - this verbose example adds clarity
let orderedPropsArr = [];
objArr.forEach((element, index, array) => {
  let tempObj = {};
  dataArr.forEach((propName) => {
    tempObj[propName] = element[propName];
  });
  orderedPropsArr.push(tempObj);
});

// console.log(orderedPropsArr);
<div id="container"></div>

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

Prevent a form from loading depending on the response received from an ajax callback

I am currently working on implementing an ajax post function. The process involves sending data and receiving a callback from PHP with some data in return. Depending on the returned data, I need to make a decision whether to proceed or allow the user to re ...

Creating an event declaration using Javascript's onclick function

As I was getting ready to add an onclick event to my element in JavaScript, a question popped into my mind regarding the efficiency of these two options: document.getElementById(myid).onclick = function(e){...} or document.body.onclick = fun ...

Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further. http://jsfiddle.net/tmyie/R5wx8/6/ var canvas = document.getElementById('canvas'), c = canvas.getContext('2d&apo ...

The Backbone model destruction URL fails to include the model's ID when trying to delete

I'm facing an issue in my app where I need to delete a model from a collection using "this.model.destroy" in my view, but it triggers a 405 response and the response URL doesn't include the model's id. According to the Backbone documentation ...

Analyzing elements within a linked list

I am looking to develop a program that identifies duplicate items within a linked list. The structure of the list is described below: typedef struct node { char *name; char *num[10]; struct node* next; }node; My objective is to compare th ...

Is there a way for me to generate an array where I can easily access a particular 'card' whenever needed? (this question pertains to the content of the post)

I've been attempting to develop a card game in Python, but I've hit a roadblock when it comes to designing the card faces as callable objects. Below is my array of heart cards (I attempted to split the card suits into four different functions). H ...

Is the process.env.NODE_ENV automatically set to 'production'?

While examining someone else's code, I noticed this particular line. if (process.env.NODE_ENV === 'production') { ... The application in question is a node.js app with express server and reactjs front-end. If we were to deploy it on Heroku ...

Refresh meta tags in a Next.js/React app

In the process of optimizing a website for SEO, I am facing the challenge of updating the meta description's content dynamically without using any third-party libraries. While I have successfully implemented the functionality, it currently requires a ...

Struggling with making changes to a instantiated "this" object within a pseudo javascript class

If you scroll down to the bottom of this post, you'll find a workaround or possible solution. I've been grappling with understanding how pseudo classes work together to achieve the task I'm attempting (explained in the code below). It might ...

Update all field values in Redux-form version 6.0 and above

I am attempting to update several values in redux-form. They are stored in a single object, and I want to replace the current redux-form state values with those from my object. One method I have tried involves using this.props.reset() followed by multipl ...

"Using JavaScript to trigger a button click event, and then

I have a question that I think may sound silly, but here it is. I have this code snippet: <script type="text/javascript"> $(document).ready(function(){ var email_value = prompt('Please enter your email address'); if(email_value !== null){ ...

What are the best ways to incorporate a theme into your ReactJS project?

Looking to create a context for applying dark or light themes in repositories without the need for any manual theme change buttons. The goal is to simply set the theme and leave it as is. Currently, I have a context setup like this: import { createContext ...

I have noticed that the baseline of a Span element has shifted after updating my Chrome browser to a version that begins with

Once I updated to chrome Version 108.0.5359.94 (Official Build) (64-bit) from 107.0.5304.87 (Official Build) (64-bit), the behavior of the span element changed drastically. It shifted its baseline when multiple spans were stacked on top of each other. Exp ...

Unforeseen issue within Vuejs-nuxt (SSR Mode) is preventing the retrieval of the UserUUID through the getter in plugins, resulting in an unexpected '

In my vuejs-nuxt project using SSR mode, I encountered an issue when trying to call a socket event. I need to pass the userID to the socket from the store. The GetUserUUID getter functions properly in all other APIs except when called from the "plugin/sock ...

Switching to a jQuery IF statement instead of a FOR loop allows for more streamlined

I recently made a request to sqlite and am fetching data using the code snippet below: var rows = results.rows; alert(rows.length); for (var index = 0; index < rows.length; index++) { var x = rows.item(index); $( ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...

Do I require two bot logins for discord.js?

Working on my discord bot, I've been trying to incorporate a script from index.js. Should I also include bot.login at the end of cmdFunctions.js? Here is the content of index.js: const Discord = require('discord.js'); const bot = new Discor ...

I am encountering an issue with this code. The objective is to determine the frequency at which a specific word appears in the provided paragraph

function processWords(){ text = document.getElementById("inputText").value; text = text.replace(/(^\s*)|(\s*$)/gi,""); text = text.replace(/[ ]{2,}/gi," "); text = text.replace(/\n /,"&bso ...

Avoiding "Origin null is not allowed" error in Express.js POST request

I am attempting to send JSON data containing a set of key and values from JavaScript to Express.JS. Following advice from other posts, I have included the use of CORS and also added res.header("Access-Control-Allow-Origin", "*");. When testing the POST r ...

Troubleshooting Yeoman and Angular: Routing troubles persist

I recently started exploring with yeoman to develop angular applications. I am facing an issue while trying to create routes using yo:angular route. After running the command: yo:angular route foo yeoman generates the following files: app/scripts/contr ...