an array or objects within another array or objects

I've been working on arrays and objects, but I'm still struggling with creating nested objects and arrays.

I have a particular array setup that I want to convert into a nested structure, but I'm finding it difficult. I'm not sure if it's even possible.

const info = [
            {
              "Date":"3/24/23",
              "Course":"BASIC ENGLISH",
              "Examiner":"Juan Ponce",
              "Participants":"Nardo Putik",
              "Examiner Approach":"3",
              "Clear explanation of topics discussed":"3",
              "Well organized activity from start to finish":"3"
            },
            {
              "Date":"3/24/23",
              "Course":"BASIC ENGLISH",
              "Examiner":"Juan Ponce",
              "Participants":"Cardo Martinez",
              "Examiner Approach":"3",
              "Clear explanation of topics discussed":"3",
              "Well organized activity from start to finish":"3"
            },
            {
              "Date":"3/24/23",
              "Course":"BASIC ENGLISH",
              "Examiner":"Juan Ponce",
              "Participants":"Ippo Kazuya",
              "Examiner Approach":"3",
              "Clear explanation of topics discussed":"3",
              "Well organized activity from start to finish":"3"
            }
        ]
        
console.log(info);

Desired Output :

const data = 
  {
    "Date" : "3/24/23",
    "Course": "BASIC ENGLISH",
    "Examiner" : "Juan Ponce",
    "Details" : 
    [{
      "Participants" : "Ippo Kazuya",
          "Examiner Approach" : "3",
          "Clear explanation of topics discussed" : "3",
          "Well organized activity from start to finish" : "3"
      },
      {
          "Participants" : "Cardo Martinez",
          "Examiner Approach" : "3",
          "Clear explanation of topics discussed" : "3",
          "Well organized activity from start to finish" : "3"
      },
      {
          "Participants" : "Nardo Putik",
          "Examiner Approach": "3",
          "Clear explanation of topics discussed" : "3",
          "Well organized activity from start to finish" : "3"
      }]
  }

Answer №1

One method that is utilized here involves the reduce() function. The main concept behind this approach is to construct a new output array by iterating through each element in the input array, checking for existing elements in the output array. If a match is found, the data is added to its respective Details. If not, a new element is created in the output array.

const result = data.reduce((a, { Date, Course, Examiner, ...rest}) => {
  const current = a.find(
    (v) => v.Date === Date && v.Course === Course && v.Examiner === Examiner
  );
  
  if (current) current.Details.push(rest)
  else a.push({ Date, Course, Examiner, Details: [rest] })
  
  return a;
}, []);

The usage of destructuring allows for capturing the remaining properties as ...rest, making it easier to append them to the Details array.


Complete snippet:

const data = [{
  "Date": "3/24/23",
  "Course": "BASIC ENGLISH",
  "Examiner": "Juan Ponce",
  "Participants": "Nardo Putik",
  "Examiner Approach": "3",
  "Clear explanation of topics discussed": "3",
  "Well organized activity from start to finish": "3"
}, {
  "Date": "3/24/23",
  "Course": "BASIC ENGLISH",
  "Examiner": "Juan Ponce",
  "Participants": "Cardo Martinez",
  "Examiner Approach": "3",
  "Clear explanation of topics discussed": "3",
  "Well organized activity from start to finish": "3"
}, {
  "Date": "3/24/23",
  "Course": "BASIC ENGLISH",
  "Examiner": "Juan Ponce",
  "Participants": "Ippo Kazuya",
  "Examiner Approach": "3",
  "Clear explanation of topics discussed": "3",
  "Well organized activity from start to finish": "3"
}];

const result = data.reduce((a, { Date, Course, Examiner, ...rest}) => {
  const current = a.find(
    (v) => v.Date === Date && v.Course === Course && v.Examiner === Examiner
  );
  
  if (current) current.Details.push(rest)
  else a.push({ Date, Course, Examiner, Details: [rest] })
  
  return a;
}, []);

console.log(result);

Answer №2

In my opinion, performing data restructuring like this in real time is not advisable because there is uncertainty regarding the uniformity of Date, Course, and Examiner values across all objects in the array.

A better strategy would be to group the objects based on a specific property, which would result in an output where the grouped values serve as keys within an object.

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

Utilizing Ajax in PHP to Upload Files

I'm encountering an issue while attempting to upload a file and send it via AJAX. The error message I am receiving is as follows: Notice: Undefined index: xlsFile in Here is the code snippet: HTML FORM : (this form is within a Modal Popup) <f ...

Managing the state of forms using NGRX and @Effects

After submitting a form and triggering an action that is caught by an effect for an http call, I am curious about how to handle the following scenarios upon completion or failure: Display a success message once the action finishes Reset all fields for fu ...

The Javascript query is returning an [object Object] data type

I am facing an issue with a JavaScript file that is querying a SharePoint list. Specifically, the Priority drop down in the query result is displaying as [object OBJECT]. I suspect it has something to do with the var query string where I have added the &ap ...

Decoding JSON Data from PHP to JavaScript using jQuery

I am currently working on an autocomplete script where I pass variables through JSON. However, I am facing a challenge in decoding the JSON data. Below is a snippet of the JSON code I have received and my goal is to convert it into a simple JavaScript arr ...

Breaking down an RxJS observable sequence into various outputs

Can a single observable flux be split into multiple other observables? For example, I have a form that users can submit. The submit action is captured by an observable, and a validator is triggered upon submission. submitAction.forEach(validate) However ...

Troubleshooting: Issue with binding nested data property using bracket access in Vue3 v-model

Having an issue in Vue3 where I am unable to bind a nested property to v-model correctly. Check out the source code below: Template: <div id="app"> <span>{{level1.level2.level3}}</span> <br/> <span>{{level1[&ap ...

JestJS: Async testing isn't halted

I am facing two issues with my jest test: Is there a way to define the Content collection only once instead of repeating it inside the test? I encountered this error: Jest did not exit one second after the test run has completed. This usually indicates ...

Setting up or modifying JQuery AJAX encoding settings

I am currently working on a simple PATCH call similar to the one below: .ajax({ url: "/foo/bar/" type: "PATCH", dataType: 'json', data: { "foo": "foosball", "bar": "bars on bars" }, ... }); After Jquery e ...

Guide on how to automatically log out a user at a designated time

I am working on a basic application with login functionality using webforms, and I want to automatically log out the user at a specific time for updates. For example, at 13:30, I need to logout the user from the website and redirect them to the login page. ...

Exploring different methods for drawing a polygon by iterating through JSON values

I am attempting to automatically draw a polygon using values stored in a database. The Python file I have returns JSON results to an AJAX call. In the AJAX success section, I need to iterate through the JSON data and automatically draw a polygon on a Googl ...

When modifying a string in React, the edit always somehow ends up at the very tail end

In my ReactJS app, I have a Material-UI input element. Everything is working well except for one issue - when I try to edit the text in the middle of the string, the cursor always jumps to the end of the string after every letter I input. I suspect this m ...

When importing OrbitControls in main.js, THREE.js does not include the EventDispatcher export

Description I've been working on integrating the OrbitControls from THREE.js into my project. However, I encountered an error message in the Google Chrome DevTools console when trying to import the OrbitControls object. The requested module '. ...

"Although Vuex data is present, an error is being logged in the JavaScript console

I'm utilizing Vuex to retrieve data from a URL and I need to use this data in computed properties in Vue.js. What could be causing the issue? <script> import {mapGetters, mapActions} from "vuex"; computed: { ...mapGetters(["ON ...

A method for accessing a text file from a pastebin using CORS

My goal is to utilize CORS for fetching code snippets from a pastebin and then executing them in a web browser. Here is some work-in-progress code: http://www.example.com/code-snippets.html The code is syntax highlighted with options to run it, etc. I ...

The JavaScript file specified in the script tag's src attribute was successfully downloaded, but it did not execute as expected after being fetched

I've implemented an ajax call using jQuery in the following manner: $.ajax({ type: 'GET', url: 'edit.htm', success: function(data){ container.html(data); }, }); After making the ajax call, the data returned includes s ...

Receiving a mysterious error despite having everything clearly defined in the JavaScript code

Attempting to create a simple jQuery plugin: HTML: <textarea> <p>Hello World!</p> </textarea> jQuery: $.fn.wysiwyg = function (options) { var e = $(this).replaceWith("<iframe>"); console.log($(this)[0].conten ...

Utilizing the zIndex property in webGL programming

I am currently working on a three.js program My main goal is to display a 2D panel in front of the three.js scene for debugging purposes. I plan to achieve this by creating a div element and adjusting its z-index to show it above the three.js canvas. Un ...

Creating customized JavaScript using jQuery for Drupal 7 Form API

Currently, I am working on developing a custom form using Drupal 7 with form API and a tableselect that includes checkboxes. I have some specific constraints for selecting the checkboxes that I intend to implement using jQuery. I created a function for han ...

Creating a wrapper function for the map method in React

When attempting to incorporate a parameter into my map function in React, I encountered an issue where the return value turned null after encapsulating it within another function. This became apparent during debugging, especially when using console.log(mar ...

How do I view a wildcard in my ID selector using jQuery?

When I want to initially hide various content scattered around the page, I usually use the following jQuery code: $('#objective_details, #time_estimate_details, #team_members_details, #resources_details').hide(); Is there a method to utilize a ...