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

Troubleshoot: Difficulty with accessing nested tag name using getElementsByTagName

I'm currently working with a div that contains a table and its data pulled from a database. <div id="content"> <table> <tbody> <tr> <th class="header" colspan="2">Food items include:</th> </tr> ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

Unique Tags and Javascript: A customized approach

In the process of developing a web application, I am aiming for high standardization. To achieve this goal, I plan to utilize custom namespace tags that will be modified by JavaScript based on their functionality. For instance: <script type="text/java ...

A Guide to Effectively Extracting Data from Second Level JSON Arrays with

Hi, I'm having difficulty fetching the two attributes under CategoryImage in the second level of the JSON array parsing. Can someone help me with this? Thank you. <script> $(document).ready(function() { var cat=""; ...

I'm having trouble mocking the image import correctly when trying to pass a test using jest with next.js. Why am I encountering this error?

Having some trouble passing a test with Jest in Next.js. The imported image doesn't seem to be mocked by Jest, and I can't figure out what's missing. Followed all the steps in the Next.js documentation. The fileMock.js is located at <rou ...

Utilizing jQuery with live content to determine dimensions as required

Within my web application, I have a page that dynamically retrieves a view with both HTML and JavaScript. The JavaScript is responsible for rendering a chart into the retrieved view. The problem arises because the chart library I am utilizing (flot) necess ...

Incorporate a fresh attribute to the JSON data in an Angular API response

I'm currently working on updating my JSON response by adding a new object property. Below is an example of my initial JSON response: { "products": [{ "id": 1, "name": "xyz" }] } My goal is to include a new object property ca ...

Why is my custom Vuelidate validator not receiving the value from the component where it is being called?

On my registration page, I implemented a custom validator to ensure that the password meets specific criteria such as being at least 12 characters long and containing at least one digit. However, I encountered an issue where the custom validator was not r ...

What is the simplest method to create a scroller for engaging narratives?

I am in the process of creating a static but responsive storytelling website using HTML. My objective is to create an effect similar to this: https://i.stack.imgur.com/zIEpU.gif The idea is to have text on the left and a *.jpg image fixed on the right. As ...

Encoding a string in JSON that contains the "#" symbol along with other special characters

The client side javascript code I have is as follows: <html> <script type="text/javascript" src="js/jquery.min.js"></script> <script> $(document).ready(function() { //var parameters = "a=" + JSON.stringify( ...

Preserving form data using JavaScript exclusively upon submission

Hey there! I'm facing a little issue with a Form that has multiple checkboxes and a piece of JavaScript code designed to save the state of each checkbox when the user hits submit. My problem is that, currently, the checkbox state is being saved even i ...

After successful sign-in, users will be redirected to the

After mainly working on mobile development, I am now diving into web development. I am currently utilizing firebase.auth() to sign in a user and I'm struggling with how to handle page redirection within my JavaScript/node application. What is the pro ...

There seems to be a problem with the external JavaScript file not functioning

After dragging and dropping the .js file into my ASP.NET project, I am facing an issue where it remains unresponsive, even though the code works fine when used inline. This problem is occurring while using VS 2017. Here is a snippet of my code: <scrip ...

including a callback in a loop

I am attempting to have jQuery delete an element after it has gone through a series of other functions, however the following code executes the remove() command before the for loop runs any iterations. function waves(){ for(i=0;i<=10;i++){ ...

Issues encountered when incorporating personalized CSS into a Vuetify element

Working with the Vuetify selector input component, v-select, and wanting to customize its style led me to inspecting it in Chrome and copying down the necessary classes. For instance, to change the font size of the active value, I utilized: .v-select__sel ...

Transmit a fixed-size array to the workforce

I need to distribute an array of size 336 into segments for my 8 workers. I want each worker to receive segments with sizes of 12, 18, 30, 36, 48, 54, 66, and 72. The pattern is to add 6 and then 12 consecutively. So far, I have managed to split the array ...

Please type the file name into the provided text box

Is there a way to automatically insert the filename of an uploaded file into an existing text input using either or valums.com/ajax-upload/? (I am working with php) For example, in a textbox: <input name="image" type="text" value="file_name" /> ...

developing a checkbox group with Vue.js

I am working with 2 arrays - one contains possible checkbox variants and the other contains already saved checked boxes. In my VUEJS template, I have created a simple example: <ul> <li v-for="cit in possable"> ...

What could be the reason for the malfunctioning of my express delete request?

When I send a delete request using Postman on my localhost, everything functions correctly. However, when trying to make the same request from my React.js client-side, it doesn't go through. Below is the API request: router.delete("/deletetransaction ...

Upload a user-sent image to a remote SFTP server for safekeeping

Can someone help me figure out how to upload a file to an SFTP remote server using ssh2-sftp-client? I am trying to retrieve the file from the user via a post request along with the destination. To process the file, I am utilizing multer. const Client = r ...