changing the sequence of key positions in an array of Objects can be done by specifying the desired key

I'm currently working on an export feature, but the data being received from the API is not in the correct sequence (the keys of the object are in an array). I need to rearrange the keys in the object so that they are in the desired order for a single row. The current data looks like this:

data = [
{
  "key4":"value4",
  "key1":"value1",
  "key5":"value5",
  "key3":"value3",
  "key2":"value2"
},
{
  "key4":"value4",
  "key1":"value1",
  "key5":"value5",
  "key3":"value3",
  "key2":"value2"
}
]

What I want as output is:

 data =[ {
    "key1":"value1",
    "key2":"value2",
    "key3":"value3",
    "key4":"value4",
    "key5":"value5"
 },
 {
    "key1":"value1",
    "key2":"value2",
    "key3":"value3",
    "key4":"value4",
    "key5":"value5"
 }
 ]

Answer №1

You can apply the combination of .map along with Object.entries and Object.fromEntries to achieve sorting based on keys:

data = [
{
  "key4":"value4",
  "key1":"value1",
  "key5":"value5",
  "key3":"value3",
  "key2":"value2"
},
{
  "key4":"value4",
  "key1":"value1",
  "key5":"value5",
  "key3":"value3",
  "key2":"value2"
}
].map((item) =>
    Object.fromEntries(
        Object.entries(item).sort(
            (a, b) => a[0].localeCompare(b[0])
        )
    )
)

console.log(data);

Answer №2

To tackle the problem, I implemented the following Angular code snippet.

const headerKeys = ["name", "age", "gender", "city", "country"];
const filteredData = [];

  originalData.forEach(item => {
    let newItem = {};
    headerKeys.forEach(key => {
    newItem[key] = item[key];
  });
  filteredData.push(newItem);
});
console.log(filteredData);

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

What is the best way to retrieve two fields from a selected material select input?

I have a dropdown menu that populates a list of companies. Currently, I am only able to retrieve either the ID or the name of the company from the selection. I need to save both the ID and name of the selected company in my Firestore collection. I attempt ...

Is it possible to toggle multiple menus programmatically at once?

In my template, I have 2 menu components set up like this: <button md-icon-button [md-menu-trigger-for]="menu"> <md-icon>more_vert</md-icon> </button> <md-menu #menu="mdMenu"> <button md-menu-item>Refresh</butt ...

How can I retrieve specific bytes from a byte array in C# when the starting byte is known?

Looking to extract specific bytes from a byte array. I have the value of the first byte I want and need x number of bytes after it. Here is an example: byte [] readbuffer { 0, 1, 2, 0x55, 3, 4, 5, 6}; byte [] results = new byte[30]; I am specifically in ...

Utilizing combinedReducers will not prompt a re-render when dispatching actions

When I refrain from using combineReducers: const store = createStore<StoreState,any,any,any>(pointReducer, { points: 1, languageName: 'Points', }); function tick() { store.dispatch(gameTick()); requestAnimationFrame(tick) ...

What's the verdict on Ajax requests in Angular 4 - is $ajax superior to $http?

Instead of using $http to fetch data, I am utilizing $.ajax({}) in Angular 4. Is this a good approach for making AJAX calls? What is the recommended method for handling this task? Currently, I am employing this particular method for my AJAX requests. $. ...

CSS file not found error: ASP.NET core and Angular unable to locate stylesheet

Recently, I encountered a puzzling issue with my ASP.NET Core web application integrated with Angular. Despite having everything set up properly, the CSS failed to load upon launching the project. Upon inspecting the console, I was faced with this error me ...

In TypeScript, a mapped type is not allowed to define properties or methods

My challenge involves defining an interface with keys that match a specific enum key type. However, when I attempt to declare this type, I encounter the following error message: A mapped type may not declare properties or methods. Below is the code snip ...

Unable to modify the numpy array into a vector shape

In my attempt to transform an array d of shape (N, 1) into a vector of shape (N,), I followed both this solution and my own experience with numpy. The code snippet I used is as follows: from sklearn.neighbors import kneighbors_graph from sklearn.datasets i ...

Event listener for iframe video player click in Angular 2+

I have a video iframe that starts playing automatically when the page loads: <section> <div class="row" > <div style="padding-top: 56.25%"> <iframe src="https://players.brightcove.net...& ...

Help with PHP printing arrays is available

I am dealing with the following array: Array ( [3] => Array ( [IDFattura] => 3 [Data_Scadenza] => 2011-06-23 [Importo] => 343.30 [IDTipo_Offerta] => A [Email] => <a href="/cdn-cgi/l/email-protection" c ...

Constructing a Collection of JLabel Components

Currently working on a project in NetBeans GUI Design where I aim to showcase 5 JLabels, each representing different values. Is there an option within the design that allows me to combine these 5 JLabels into one array of Labels? ...

The defaultRowRenderer is causing issues with my Jest unit test. It seems to be related to an object with an anonymous import of createMulti

Encountering a failure in jest unit-tests when using the defaultRowRenderer method in react-virtualized for a Table component, with the error message: ...node_modules\react-virtualized\dist\es\Table\index.js:1 ({"Object.<anonym ...

Can dynamic values be sent to a custom form validator in Angular 6?

Essentially, I am facing a challenge with validating form inputs that are interdependent (for example, ensuring that the "from" time is earlier than the "to" time). However, I'm unsure of the best approach to tackle this issue. Below is my form group ...

Angular with RxJS: Observable with synchronous data flow

One of the services I have includes a method called foo. In this method, I am subscribing to an observable (http-client). foo () : boolean { let ret : false; this.http.get ("/blabla").subscribe ( (resp) => { ret = true; } return ret; ) ...

Develop a directive for transforming data

In my latest project, I am looking to develop a LoaderDirective that can fetch an observable, display a spinner while loading the data, and then switch to showing the actual data once loaded. I also want it to expose the loaded data using the 'as&apos ...

Ways to prevent encountering an npm error during the installation of a new package in an Angular application

For my Angular Application to update the date-time range picker, I needed to install an npm package. I opted to use ng2-daterangepicker, but encountered an error while trying to install its package. The error displayed is as follows : PS C:\Users&bso ...

Transferring information between screens in Ionic Framework 2

I'm a beginner in the world of Ionic and I've encountered an issue with my code. In my restaurant.html page, I have a list of restaurants that, when clicked, should display the full details on another page. However, it seems that the details for ...

Tips for converting text input in a textbox to a Date value

My knowledge of Angular is limited, and we are currently using Angular 10. In our application, there is a textbox where users need to input a date in the format 10202020. This value should then be reformatted as 10/20/2020 and displayed back in the same ...

What is the correct way to send a basic array through an AJAX call?

I have the code below: $("form").submit(function(e) { e.preventDefault(); var answers = new Array(); for (var j = 0; j <= i; j++) answers[j] = [($("[name=ris" + j + "]").val())]; $.ajax({ url: "crea_sondaggio.php ...

What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation. In the Angular 11 demo, scrolling functions perfectly an ...