Combining arrays in a unique manner within a React app using JavaScript

I am encountering an issue while attempting to populate a table with rows and checkboxes using the .map method. The problem arises when I try to create an array by combining two arrays obtained from the database - JournalA and JournalB.

Journal_A

[
  {STUDENT_NAME: "data1",
   STUDENT_SECOND_NAME: "data",
   STUDENT_LAST_NAME: "data",
   STUDENT_PHOTO: "data"
  },
  {STUDENT_NAME: "data2",
   STUDENT_SECOND_NAME: "data",
   STUDENT_LAST_NAME: "data",
   STUDENT_PHOTO: "data"
  },
  {STUDENT_NAME: "data3",
   STUDENT_SECOND_NAME: "data",
   STUDENT_LAST_NAME: "data",
   STUDENT_PHOTO: "data"
  }
]

Journal_B

[{
  JOURNAL_DATA: "{
  "1": false,
  "2": false, 
  "3": false
  }"
}]

The desired output should be as follows

[
  {STUDENT_NAME: "data1",
   STUDENT_SECOND_NAME: "data",
   STUDENT_LAST_NAME: "data",
   STUDENT_PHOTO: "data",
   BOOL:true
  },
  {STUDENT_NAME: "data3",
   STUDENT_SECOND_NAME: "data",
   STUDENT_LAST_NAME: "data",
   STUDENT_PHOTO: "data",
   BOOL:false
  },
  {STUDENT_NAME: "data2",
   STUDENT_SECOND_NAME: "data",
   STUDENT_LAST_NAME: "data",
   STUDENT_PHOTO: "data",
   BOOL:true
  },
]

I have attempted to use concat() and push(), however, React does not seem to work well with them =(

let i = 0;
for (i=0; i<JournalA.length; i++){
    console.log(JournalA.map[i].concat(JournalB.concat[i]));
}

Answer №1

Is this the solution?

const StudentJournal = [
  {STUDENT_NAME: "John",
   STUDENT_SECOND_NAME: "Doe",
   STUDENT_LAST_NAME: "Smith",
   STUDENT_PHOTO: "photo1"
  },
  {STUDENT_NAME: "Jane",
   STUDENT_SECOND_NAME: "Doe",
   STUDENT_LAST_NAME: "Johnson",
   STUDENT_PHOTO: "photo2"
  },
  {STUDENT_NAME: "Alice",
   STUDENT_SECOND_NAME: "Doe",
   STUDENT_LAST_NAME: "Williams",
   STUDENT_PHOTO: "photo3"
  }
]


const JournalData = [{
  JOURNAL_DATA: '{"1": false, "2": false, "3": false}'
}]

const jData = JSON.parse( JournalData[0].JOURNAL_DATA)

const updatedResult = StudentJournal.map( ( student, index ) => {
  student.BOOL = jData[ index + 1 ]
  return student
} )

console.log(updatedResult)

Answer №2

Explore alternative methods instead of using a for loop

let merged_array = Journal_A.map((a, c) => ({
    ...a,
    BOOL: Journal_B[0][c + 1]
}))

UPDATE

Upon further examination, I realized that Journal_B is an object. Attempting to merge an array with three elements with another array containing only one element may not be the most efficient approach. It might be helpful to simplify the structure.

UPDATE 2

There seems to be a syntax error following the adjustment made to Journal_B

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

Integrating a search box with radio buttons in an HTML table

I am currently working on a project that involves jQuery and a table with radio buttons. Each button has different functionalities: console.clear(); function inputSelected(val) { $("#result").html(function() { var str = ''; ...

What are the distinctions between executing a c++ function and a JavaScript function?

After attempting to execute the c++ program provided below, a compilation error occurred. However, when trying to execute the second javascript code snippet below, no errors were detected. Why is this? ////c++//// #include<iostream> using namespace ...

In jqGrid's gridComplete event, we can use the getRowData method to retrieve the value of a

Seeking guidance on extracting variables from jqGrid getRowData method While iterating through rows, I simply want to retrieve the ID and Phrase column values into separate variables gridComplete: function () { var allRowsInGrid = $('#list'). ...

php PHP code for rotating an array

If you have two integer arrays, how can you determine if the second array is a rotated version of the first array and which specific PHP function would you need to use for this? For example: Original Array A=[1,2,3,4,5,6,7,8] Rotated Array B=[6,7,8,1,2,3, ...

Reset the tabulator with updated data and a revised column setup on the existing DOM element

Currently, I am utilizing the tabulator jQuery plugin for a project. My goal is to re-initialize the tabulator on the same div element but with a different column configuration and dynamic data. I have provided a sample div and script below that shows wh ...

What is the best way to determine if an array exhibits a "wavy" pattern?

I need my code to determine if an array is 'wavy', meaning the first element is less than the second, the second is greater than the third, and so on until the end of the array. However, my current code is not working properly. Here is the code s ...

Implementing dynamic button visibility based on specific conditions in EJS Template

I am looking to include an ADMIN DASHBOARD button in the dashboard navbar, but with a condition that it should only be visible if the user has the role of Admin. I have added the necessary condition (code provided below), however, it seems to not be functi ...

Utilizing PHP to add numerous markers on Google Maps

I've been searching through various resources and forums but haven't been able to find a solution for my specific situation. I'm currently learning PHP and Javascript, so my code might not be perfect, but here is what I have: So far, I have ...

Checking for date overlap between two textboxes in MVC5 when searching against a date field

Currently, I am exploring options to implement search filters for my model results. I have a field called RunDate and I intend to allow users to search between two dates using two textboxes. @Html.TextBox("StartDate", null, new { @class = "datefield form- ...

Struggling to get a price calculator up and running efficiently

The code I have should be functioning, however, when I insert it into the code module in the Divi theme on WordPress, it doesn't work. Interestingly, when I try it in a notepad, it works perfectly fine but fails to function on the website itself. () ...

TypeError is encountered while attempting to verify cookies

I created a function like this: const token = req.cookies['SESSION_DATA'] if (token) { ... } catch (err) { ... } However, when I try to check for a token, I receive a TypeError stating "Cannot read property of undefined." Interestingly, the same ...

a method for inserting a space after a certain character, with the exception of when that character is located at the start or end of a line

I've created a regular expression that can modify various patterns like: anything1 * anything2* anything3 anything1* anything2 * anything3 anything1 * anything2 * anything3 anything1*anything2 *anything3 anything1 * anything2 *anything3 anything1*any ...

Issue encountered while attempting to install Parcel, with errors being triggered in the parcelwatcher and in the process of

1 npm ERR! path C:\Users\USER\OneDrive\Documents\My sites\Music Website\node_modules@parcel\watcher npm ERR! command failed npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-gyp rebuild npm ER ...

While using .map() to display videos from an array, the button ends up playing all videos instead of only the selected

Within this component, I am presenting an array of YouTube videos utilizing react-player. The issue I'm facing is that when the custom play button is clicked, all videos in the array play and pause instead of just the selected one. I am currently uti ...

Prevent clicks from passing through the transparent header-div onto bootstrap buttons

I have a webpage built with AngularJS and Bootstrap. It's currently in beta and available online in (German and): teacher.scool.cool simply click on "test anmelden" navigate to the next page using the menu This webpage features a fixed transparent ...

Utilize the zoom functionality on an SVG that is already in place (using d3.js v4

I have been attempting to create a zoomable SVG using d3.js (version 4). You can view my progress here: JSFiddle HTML <svg id="mySVG" width="800px" height="600px" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); background: lightgrey;"> < ...

What is the best way to convert base64 into an image using Node.js?

I'm having trouble with decoding an image sent as base64 through sockets. The file that should contain the image is being written as a base64 string instead of a jpg file. For encoding through socket: function encode_base64(filename) { fs.readFile( ...

Implement a logging system to track and record data from both incoming requests and outgoing responses on a server powered by Express and Node.js

Is there a way for my server to log the response and request data when posting to another server? Thank you. const request = require('request'); postToIotPlatform = function postToIotPlatform(req, res, next) { var formData = JSON.stringify( ...

Combine a variety of small 2D matrices to create a larger one

Looking to interlace small matrices into a larger one? Imagine having 4 matrices of size 4x4, and you want to combine them to create an 8x8 matrix like the image below: https://i.sstatic.net/MLZGy.png The order in which the small matrices are obtained det ...

difficulties encountered while generating json file using arrays

I am attempting to save this playlist file, similar to the one shown below, in an albums.json file but am encountering difficulties. I also want this json object to be unique. If anyone can provide guidance on the right way forward, I would greatly appreci ...