Arrange the items in an array that are equal to a single object within the array

My Fetch request is returning an array of objects structured like this:

[
   {"id":11,"name":"test1","day":"MON","level":2},
   {"id":13,"name":"test2","day":"TUE","level":3},
   {"id":14,"name":"test1","day":"WED","level":4},
   {"id":15,"name":"test2","day":"FRI","level":5}
]

Within this array, there are four objects, two of which have the same name. To organize the result accordingly, it should look like this:

 {
           "test1" : [
                       {"id":11,"name":"test1","day":"MON","level":2}, 
                       {"id":14,"name":"test1","day":"WED","level":4}
                    ],
           "test2" :[
                      {"id":13,"name":"test2","day":"TUE","level":3}, 
                      {"id":15,"name":"test2","day":"FRI","level":5}
                    ]
  }

Answer №1

Utilize the reduce method for this task

const data = [
   {"id":11,"name":"test1","day":"MON","level":2},
   {"id":13,"name":"test2","day":"TUE","level":3},
   {"id":14,"name":"test1","day":"WED","level":4},
   {"id":15,"name":"test2","day":"FRI","level":5}
];

const result = data.reduce((accumulator, current) => {
    accumulator[current.name] = accumulator[current.name] || [];
  accumulator[current.name].push(current);
  return accumulator;
}, {})

console.log(result);
console.log(Object.values(result).flat());

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

A captivating opportunity for a web developer specializing in frontend design

Encountered an intriguing dilemma that has me stumped. There is a single stipulation: Only the json can be altered! I am struggling to meet this requirement: data.hasOwnProperty("\u{0030}") class JobHunter { get data() { return &ap ...

Tips for Deactivating One Button While Allowing Others to Remain Active

Whenever the $order_status is marked as Accepted, only the button labeled Accept should be disabled. If the $order_status changes to Dispatched, then the button that should be disabled is labeled as Sent. However, if the status is Cancelled, then the butto ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Performing an Ajax request to the server and then sending the retrieved data back to Charts.js

After extensively researching ajax, php, and related topics, I'm facing a challenge. I want to take an array retrieved from my database and integrate it into a chart.js script. The data retrieval seems fine as per Firebug inspection, but the issue ari ...

Setting up an Express route with dynamic parameters in Node.js

I am in the process of creating a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I'm working on setting up an Express route that will retrieve specific data from MongoDB based on the provided ID. Here is the current code snippet for the ro ...

What is the best way to update the value of a JSON node using Ruby?

In my Ruby code, I am working with a JSON string that I successfully load as a JSON Hash using the following method: @json_hash = Json.parse(json_string) The content of 'json_string' is quite simple: {"key1"=>"string_value_1", "key2"=1000} ...

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Ways to transmit information among Vue components

I am trying to figure out how to pass data from the Module variable in CoreMods.vue to ExternalWebpage.vue using Vuex. I want the CoreModule state to be watched for changes in the external webpage. This is my store.js setup: import Vue from 'vue ...

Steps for retrieving JSON data from REST API on on-premise TFS

We are utilizing on-premise TFS Version 15.105.25910.0, also known as TFS 2017, to retrieve JSON data (specifically for a given Work Item id) using Postman for sending/receiving requests. Initially encountered permission denied errors which were resolved ...

Regarding passing input into a JavaScript class method that is exported through the exports keyword

The inquiry at hand relates to ExtendScript code, however, I believe it should be independent of any specific javascript implementation. If we have the following in a JS library file (base64.js) exports.encode64 = encoder('+/'); //... function ...

AngularJS - choosing the ng-model's index value

I'm looking to retrieve the selected item(s) from a select control along with their values or titles. Once the user has made their selections from the dropdown menu, I want to be able to determine the number of items selected and display their titles ...

Ensure to verify if any array indexes are empty in VBA, including the possibility of containing objects

Is there a way to accurately check for empty indexes in a Variant array without triggering exceptions for regular data types? I currently use Is Nothing to identify empty indexes that contain objects, but it causes issues with non-object data types. Here i ...

Shrink Font-Awesome icon sizes using a Node.js and Express.js web application

Currently, I am in the process of developing a website using node.js + express.js and implementing font-awesome for icons. The local hosting of Font-awesome has resulted in a 1.2 MB JS file [font-awesome.js], even though we are only utilizing 10-15 icons. ...

AngularJS fails to prioritize the following element

Here is my HTML code: <div ng-app="app"> <form> <div class="form-group"> <label >Username</label> <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/> ...

Creating an object using JSON and implementing custom methods in Javascript

When making a $.ajax request to an API, I receive a chunk of JSON data. The JSON looks something like this: var result = { "status": 200, "offset": 5, "limit": 25, "total": 7, "url": "/v2/api/dataset/topten?", "results": [ { "d ...

Error: The method .map is not a valid function in this context

I've decided to build a small To-Do app in order to enhance my knowledge of ReactJS and React Hooks. However, I'm facing an issue with the list.map() function that I'm using. The error message keeps saying that it's not a function, but ...

Tips for effectively utilizing vue-draggable (or Sortable JS) within a v-data-table using the powerful combination of Vuetify 2 and Vue JS 2

I'm currently experimenting with integrating vue-draggable into Vuetify's v-data-table based on the instructions provided in this article : https://medium.com/vuetify/drag-n-drop-in-vuetify-part-ii-2b07b4b27684 The article mentions : "The main o ...

Most efficient method for nesting child objects within an array of objects using JavaScript

Hey experts, I'm on the hunt for the most efficient method to transform this data: [ { "id": 1, "animal": "cat", "age": 6, "name": "loky" }, { "id": 2, "animal": &quo ...

What strategies can I implement to integrate Cordova with a combination of Meteor and React?

I'm currently struggling to implement a Cordova plugin with Meteor and React. According to the documentation: You should wrap any functionality that relies on a Cordova plugin inside a Meteor.startup() block to ensure that the plugin has been fully ...