I am interested in using the split method to separate and then mapping an object in JavaScript

Need assistance on separating an array using the split method. The array contains objects with properties such as name, course1, course2, and course3. Only the courses with text in their content along with a plus sign should be separated into an array using the split property. Each course object should include its identifier, credit, and note. Here is the original array:

Please help me, thank you.

I attempted to write some code but it's not working for me

//this is my array
var student: [
          {
          'name' : 'ivan hambi apaza',
          'course1' : 'HISTORIA DE LA DANZA+2+16',
          'course2' : 'HISTORIA+3+17',
          'course3' : '',
          }
],
       
//a step that I was doing but it does not come out
studentCourses(){
var newArr = [...this.student]
              newArr.map(el => {
              return el.course1 = el.course1.split('+')
              })
              newArr.map(el => {
              return el.course2 = el.course2.split('+')
              })
              newArr.map(el => {
              return el.course3 = el.course3.split('+')
              })
              
    return newArr
}

  
console.log(studentCourses())

Expected result:

[
  {
      'name':'ivan hambi apaza',
      'courses':[
               {'course':'HISTORIA DE LA DANZA','credit':2,'note':16},
               {'course':'HISTORIA','credit':3,'note': 17},
              ]
  }
]

Answer №1

Give this code a shot. It utilizes some cool ES6 features like destructuring and object property-value shorthand:

// 'HISTORIA DE LA DANZA+2+16' => {'course':'HISTORIA DE LA DANZA','credit':2,'note':16}
function convertToCourse(c) {
   if (c.length === 0) return null
   var [course, credit, note] = c.split(""+"")
   return {course,credit,note}
}

// {name:...,course1:...,course2:...,...} => ['HISTORIA DE LA DANZA+2+16',...]
function objectsToCourses(o) {
   // return [o.course1,o.course2,o.course3] // sufficient ???
   var result = []
   for (var key in o) {
      if (key.startsWith("course")) result.push(o[key])
   }
   return result
}

// main object conversion function
function arrayToObject(o) {
   var courses = objectsToCourses(o) // extract courses from o
   courses = courses.map(convertToCourse) // convert strings to objects
   courses = courses.filter(Boolean) // filter non-null courses
   return {name: o.name, courses: courses}
}

// main function, simply maps the array
function studentArrayToObjects(list) { return list.map(arrayToObject) }


// test
var students = [
   {
      'name' : 'ivan hambi apaza',
      'course1' : 'HISTORIA DE LA DANZA+2+16',
      'course2' : 'HISTORIA+3+17',
      'course3' : '',
   },
]
console.log(studentArrayToObjects(students))
console.log(studentArrayToObjects(students)[0].courses)

Answer №2

If you want to extract course objects, you can use a combination of flatMap and reduce along with a custom function.

var student = [ { name: "ivan hambi apaza", course1: "HISTORIA DE LA DANZA+2+16", course2: "HISTORIA+3+17", course3: "", } ];

getFormattedCourse = (course) =>
  /\+/g.test(course) 
    ? ((arr = course.split("+")),  
      { course: arr[0], credit: arr[1] || "0", note: arr[2] || "0" }) 
    : { course: course, credit: 0, note: 0 }; 

result = student.flatMap(({ name, course1, course2, course3 }) => 
  Object.values(
    [course1, course2, course3].reduce( 
      (acc, item) => (
        item != "" 
          ? !acc[name] 
            ? (acc[name] = { ...acc[name], name: name, courses: [getFormattedCourse(item)] }) 
            : acc[name].courses.push(getFormattedCourse(item)) 
          : acc,
        acc
      ),
      {}
    )
  )
);

console.log(result);

Answer №3

It appears that this solution will meet your needs.

function parseStudent(student) {
        let finalList = [];
        for(let i=0;i<student.length;i++) {
            let entry = student[i];
            let formattedEntry = {
                name : entry.name,
                courses : []
            };
            delete entry.name;
            Object.keys(entry).forEach(key => {
          if(entry[key].trim().length === 0) return;
                let data = entry[key].split('+');
                let courseData = {
                    course: data[0],
                    credit: data[1] ? data[1] : "",
                    note: data[2] ? data[2] : ""
                };
                formattedEntry.courses.push(courseData);
            });
            finalList.push(formattedEntry);
        }
        return finalList;
    }

    let student = [
            {
              'name' : 'ivan hambi apaza',
              'course1' : 'HISTORIA DE LA DANZA+2+16',
              'course2' : 'HISTORIA+3+17',
              'course3' : '',
            }
    ];

    console.log(parseStudent(student));

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

Is it possible to programmatically refresh an Angular controller?

Within my HTML page, I have implemented three tabs with each tab linked to a unique controller. The structure is as follows: MainHTML (app.pages.managing.html): <div id="DetailsViewContainer"> <div ng-if="selectedTab === 'tab1&a ...

Utilizing FullCalendar for showcasing comprehensive details

I'm a big fan of the fullcalendar plugin and all its amazing features. I want to enhance it by displaying more customized information for each event when in agendaWeek or agendaMonth view. Switching between views is easy, but I need help filtering out ...

What is the best method to transfer information from a What You See Is What You Get editor to a database using Vue.js?

I have recently started using the Vue2Editor in order to streamline my process of sending text and image data to my Firebase database. However, I am encountering an issue where the entered data is not being added successfully. Previously, with traditional ...

What is the best method for managing file storage and retrieval in web applications that only run on the client-side?

I'm currently working on an application where users can create their own data. Without a backend or database, all the information is stored within the user's session. My preferred solution involves: User interacts with the app, clicks "Save", ...

Display a PHP array with my customized formatting

Hello, I'm struggling with a php code that is supposed to retrieve data from a table and display it in a structured format. My goal is to have the output look something like this: id|name|id|name|id|name. However, I've tried using the implode() m ...

Guidelines on populating a Vue array with data fetched from an Axios request

The v-breadcrumbs component is used to display data from the breadcrumbs array, which works seamlessly with static data. <v-row> <!-- Breadcrumbs --> <v-col class="d-flex"> <v-breadcrumbs :items="breadcrumbs"></v ...

Tips for using JavaScript to style an array items individually

I have currently placed the entire array within a single div, but I would like to be able to display each element of the array separately so that I can style "date", "title", and "text" individually. This is my JSON structure: [ { "date": "Example ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...

an occurrence of an element being rendered invisible, within an instance of an element being rendered as flexible,

I am trying to create a button that will show a list of elements. Within this list, there is another button that can be used to either close the list or hide it entirely. However, for some reason, my code is not functioning properly. let btn1 = documen ...

Error: The react.js application is unable to access the property 'classList' of a null object

I've encountered a bug that's been causing me some trouble. Every time I try to run my react application, I keep getting an error message that reads TypeError: Cannot read property 'classList' of null. As someone who is new to react, I& ...

Adding a new column to a table that includes a span element within the td element

I am attempting to add a table column to a table row using the code below: var row2 = $("<tr class='header' />").attr("id", "SiteRow"); row2.append($("<td id='FirstRowSite'><span><img id='Plus' s ...

The UI Bootstrap Datepicker requires a second click in order to update the month

I am currently using the UI Bootstrap Datepicker component. An issue arises when I try to select the next month - the datepicker itself updates correctly, but the displayed month name does not change (refer to picture 1 and 2). Interestingly, after select ...

Generating a NumPy array from a list using operations

I retrieved data from an SQLite database stored in a Python list with the following structure: # Here is an example data = [(1, '12345', 1, 0, None), (1, '34567', 1, 1, None)] My goal is to convert this list of tuples into a 2D NumPy a ...

The act of initiating a click on a radio button involves evaluating conditions prior to toggling

Apologies for the slightly ambiguous title, let me provide a clearer explanation. I have created a codepen to demonstrate an issue that I am facing. You can view it here. In my codepen, I have two toggle buttons labeled "Male" and "Female" for simplicity. ...

Effective ways to engage with a window that is supervised by a different controller?

Although the question may appear vague initially, I struggled to find a better way to convey my idea. Let me elaborate on it in detail. In my SPA application, I have MasterController connected to the <html> tag. This MasterController consists of all ...

Different approaches to transforming jQuery code into functional AngularJS code

I am a beginner in AngularJS and I'm looking to implement functionality for a login page similar to the one you see when you click the 'Forgot Password' link: Would it be more appropriate to use a directive instead of a controller for this ...

The error in React syntax doesn't appear to be visible in CodePen

Currently, I am diving into the React Tutorial for creating a tic-tac-toe game. If you'd like to take a look at my code on Codepen, feel free to click here. Upon reviewing my code, I noticed a bug at line 21 where there is a missing comma after ' ...

Mozilla browser experiencing issues with mouse move event functionality

Here, I have a background image on the body and with the following script, when the user moves the mouse, the image in the background also moves. body { background-image: url('../images/1.png'); background-size: 98%; background-posi ...

Guide to assigning a value to a model in AngularJS by utilizing a select input with an array of objects

I'm new to AngularJS and I've encountered a challenge that requires an elegant solution. My application receives a list from the server, which is used as the data source for the select tag's options. Let's assume this list represents a ...

Looping Feature in Ionic Framework's Slides Component

Currently, I am working on developing an application using Ionic-Angular. When it comes to incorporating slides in my app, I opted for the ionic 4 ion-slides component. Everything was going smoothly until I wanted to enable looping for the slides so that u ...