Rearrange a set of elements based on specific criteria

I am completely lost when it comes to deciding on a suitable title for this piece. Here is the information I have retrieved from the API:

[
    {
      "order": 1,
      "role": {
        "label": "singer"
      },
      "artist": {
        "name": "AaRON"
      }
    },
    {
      "order": 1,
      "role": {
        "label": "author"
      },
      "artist": {
        "name": "Simon Buret"
      }
    },
    {
      "order": 2,
      "role": {
        "label": "author"
      },
      "artist": {
        "name": "Olivier Coursier"
      }
    },
    {
      "order": 1,
      "role": {
        "label": "composer"
      },
      "artist": {
        "name": "John Doe"
      }
    }
  ]

And here is the format in which I need to send the data:

"artist": {
  "singer": [
    "AaRON"
  ],
  "author": [
     "Simon Buret",
     "Olivier Coursier"
  ]
}

The order property needs to be considered in the process.

For instance, Simon Buret should appear first as his order is set to 1.

I am clueless about how to go about implementing this, I attempted a map function but I am unsure of what should be included inside it :/

this.artistControl.controls.map(artistControl => {
   ...
});

Is there any way to achieve the desired outcome?

Answer №1

Would you like to try this solution:

let musicians = [
    { "ranking": 1, "role": { "label": "singer" }, "artist": { "name": "AaRON" } },
    { "ranking": 1, "role": { "label": "author" }, "artist": { "name": "Simon Buret" } },
    { "ranking": 2, "role": { "label": "author" }, "artist": { "name": "Olivier Coursier" } },
    { "ranking": 1, "role": { "label": "composer" }, "artist": { "name": "John Doe" } }
];

let data = {'artist': {}};
musicians.forEach(m => {
    data['artist'][m.role.label] = data['artist'][m.role.label] || [];
    data['artist'][m.role.label][m.ranking-1] = m.artist.name;
});

console.log(data);

Answer №2

To achieve this, you can utilize the `reduce` method by using an object as an accumulator parameter. Then, you can verify if the key does not exist, create it with an empty array as the value, and proceed to add names in order.

const data = [{"order":1,"role":{"label":"singer"},"artist":{"name":"AaRON"}},{"order":1,"role":{"label":"author"},"artist":{"name":"Simon Buret"}},{"order":2,"role":{"label":"author"},"artist":{"name":"Olivier Coursier"}},{"order":1,"role":{"label":"composer"},"artist":{"name":"John Doe"}]

const result = data.reduce((r, {
  role: { label },
  artist: { name },
  order
}) => {
  if (name) {
    if (!r[label]) r[label] = [];
    r[label][order - 1] = name;
  }
  
  return r;
}, {})

console.log(result)

Answer №3

let bandMembers = [{"order":1,"role":{"label":"singer"},"artist":{"name":"John Legend"}},{"order":1,"role":{"label":"guitarist"},"artist":{"name":"Tom Morello"}},{"order":2,"role":{"label":"bassist"},"artist":{"name":"Flea"}}];

const bandRoles = bandMembers
  .sort((member1, member2) => member1.order - member2.order)
  .reduce((acc, { role, artist }) => ({
    ...acc,
    artist: {
      ...acc.artist,
      [role.label]: [
        ...(acc.artist[role.label] || []),
        artist.name,
      ],
    },
  }), { artist: {} });
  
console.log(bandRoles);

Answer №4

Check out this new es5 implementation!

const records = [{ "order": 1, "role": { "label": "singer" }, "artist": { "name": "AaRON" } }, { "order": 1, "role": { "label": "author" }, "artist": { "name": "Simon Buret" } }, { "order": 2, "role": { "label": "author" }, "artist": { "name": "Olivier Coursier" } }, { "order": 1, "role": { "label": "composer" }, "artist": { "name": "John Doe" } }];

 var finalResult = records.reduce(function(mapObj, item) {
            mapObj["artist"] = mapObj["artist"] || {};
            if (item.role.label === 'author' || item.role.label === 'singer') {
                mapObj["artist"][item.role.label] = mapObj["artist"][item.role.label] || [];
                mapObj["artist"][item.role.label][item.order - 1] = item.artist.name;
            }
            return mapObj;
 }, {});
        
 console.log(finalResult)

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

Incorporate highcharts data into your Laravel project using the power of AJAX

Encountering an issue with loading data for a Highcharts chart. The response from my controller provides the following data: [['Doctorado', 91.86],['Maestría', 6.98],['Licenciatura', 1.16]] Although the AJAX call is succes ...

Combining two input text strings

A React component I'm working on takes the user's first and last name to create unique usernames for them. class App extends Component { render() { return ( <div className="App"> First name:<br/> <input ...

The async waterfall is encountering a Typeerror due to the nextcallback function not being defined properly

async.waterfall([1,2,3,4].map(function (arrayItem) { return function (lastItemResult, nextCallback) { // performing the same operation for each item in the array var itemResult = (arrayItem+lastItemResult); // pa ...

Transferring a parameter from link_to to a popup window in a Rails application

I am facing an issue with passing an object to my modal in Rails. The object has a table of results with an attribute "email", but I seem unable to pass it so that I can use it within my modal. index.html.erb <div class="modal fade bs-example-modal-lg ...

Update the div element without needing to reload the entire page

Is there a way to reload a div tag without refreshing the entire page? I understand this question has been asked before, but I want to make sure I have a clear understanding. <p>click HERE</p> <div class="sample"> <?php functi ...

What happens when Google Polymer platform is used without defining _polyfilled?

My attempt at creating a simple example using Google Polymer's platform.js is running into an error message that says: Uncaught TypeError: Cannot read property '_polyfilled' of undefined This is what I'm attempting to achieve: <cur ...

Discover the method for inserting a title attribute value into a span element

Utilizing AngularJS to retrieve and display data within a span element. I am now aiming to utilize this value as the title for another span element. The current code being used is shown below: <span style="display: inline-block; width: 160px">{{acti ...

Compiling modal window content in AngularJS can lead to the creation of controllers that are left disconnected

I implemented a modal window triggered by fancybox in my project. Once the modal is displayed, fancybox triggers a "modalShown" event that is listened for by AppController. In this listener, $compile is called on the modal content to create the ModalContro ...

When the ajax.beginform is successful, no action is required

Hey there, I've been attempting to utilize ajax.beginform in my asp.Net MVC project to trigger an alert upon success. However, I've hit a roadblock as I can't seem to get it working and no error messages are appearing either. [HttpPost ...

Require.js and R.js optimizer overlooks shimming configuration

I am facing an issue where R.js is not loading my shim properly, causing jQuery to load before tinyMCE which results in tiny being initialized before it has fully loaded. How can I resolve this problem? build-js.js: var requirejs = require('requirej ...

Submission event linked with AJAX code fails to execute

Having trouble submitting a form within an ajax success function: $('#formId').on('submit', function (e) { e.preventDefault(); }); $('#submit').on('click', this.doStuff); doStuff: function () { $.get(&ap ...

Suggestions for rectifying the calculation script to include the price, a phone number, 2 digits, and integrating a textfield for cost

I have developed a script that calculates prices, phone numbers, and extracts the last 2 digits from the phone number. In my website, the price is displayed through a select option. However, I am facing an issue where the cost does not automatically updat ...

Waiting for the HTTP response in NodeJS before sending the next request

I'm currently struggling with my NodeJS code. I am attempting to send an HTTP Request to a REST API, which will respond with a new URL. Once I receive this URL, I need to make another request to that specific URL and continue the process. My current ...

Is there a way to change the screen upon clicking a button?

On my website, I have a simplified "login" screen where users only need to enter their name. There is a button on this screen, but no navigation links. I would like to create another screen with different content that appears when the button is clicked, bu ...

Guide on transforming a tuple of random types into a nested type structure with the help of recursive conditional types

When I responded to the query on whether Typescript Interfaces can express co-occurrence constraints for properties, I shared the following code snippet: type None<T> = {[K in keyof T]?: never} type EitherOrBoth<T1, T2> = T1 & None<T2&g ...

Tips for seamlessly transitioning the background of Google Maps into view as you scroll down the page

I have a unique background with a Google Map. It loads perfectly in the right place when I open the page, but as I scroll down, it disappears from view. Is there a way to keep the Google map constantly in the background, even when scrolling? This is my cu ...

What is the reason for index.html requesting the css or js modules as if they were directories when loading?

I am currently developing a server using expressjs: 'use strict'; var express = require('express'); var logger = require('morgan'); var path = require('path'); var bodyParser = require('body-parser'); va ...

What is the best way to restore the original form of a string after using string.replaceAll in javascript

To ensure accurate spelling check in JavaScript, I need to implement text normalization to remove extra whitespaces before checking for typos. However, it is crucial to keep the original text intact and adjust typo indexes accordingly after normalization. ...

Modifying preset values in settings.json within the [Extension Development Host] environment

Currently, I am developing an extension in VS Code and I want to implement a feature where a pop-up with a text message input appears when the extension first runs. The user input from the pop-up will be used to modify the default settings in the settings. ...

Having trouble updating attribute through ajax requests

How can I set attribute values using ajax-jquery? Here are some snippets of code: HTML_CODE ========================================================================== <div class="col"> <ul class="nav nav-pills justify-content-end& ...