Tips for transforming intricate JavaScript arrays into a unified array and iterating through to create a table

I need help combining two arrays that contain objects and reassigning the values in a standard format. Can anyone provide some guidance? Thank you.

Here is my current situation:

array1 = [{Apple: Ken,  Orange: Mary, Melon: Tina, Strawberry: Jessica, Mango: Susana, Lemon: Julia}]
array2 = [{Apple: 12,  Orange: 6, Melon: 7, Strawberry: 16, Mango: 15, Lemon: 11}]

Desired outcome:

arrayCombined = [[Apple: Ken, 12],[Orange: Mary, 6], [Melon: Tina, 7], [Strawberry: Jessica, 16], [Mango: Susana, 15], [Lemon: Julia, 11]]

Intended table display:

Fruit      | Fruit(buyer)  | Fruit(number of purchase) | even-number prize
---------------------------------------------------------------------
Apple      |   Ken         |     12                    |     Yes        
Orange     |   Mary        |      6                    |     Yes  
Melon      |   Tina        |      7                    |      No  
Strawberry |   Jessica     |     16                    |     Yes  
Mango      |   Susana      |     15                    |      No  
Lemon      |   Julia       |     11                    |      No  

       

Answer №1

If your data is structured correctly as shown below:

const fruits = [{Apple: 'Ken',  Orange: 'Mary', Melon: 'Tina', Strawberry: 'Jessica', Mango: 'Susana', Lemon: 'Julia'}]
const fruitCounts = [{Apple: 12,  Orange: 6, Melon: 7, Strawberry: 16, Mango: 15, Lemon: 11}]

You can utilize Object.entries() to generate an array containing key-value pairs from the first array. Then, by using map, you can transform this array into the 'combined array' with the desired format. Here is a suggestion on how to achieve this:

const fruits = [{Apple: 'Ken',  Orange: 'Mary', Melon: 'Tina', Strawberry: 'Jessica', Mango: 'Susana', Lemon: 'Julia'}]
const fruitCounts = [{Apple: 12,  Orange: 6, Melon: 7, Strawberry: 16, Mango: 15, Lemon: 11}]

const combinedArray = Object.entries(fruits[0])
  .map(([fruit, person]) => {
    const count = fruitCounts[0][fruit];

    return { [fruit]: [person, count] };
  })

console.log(combinedArray);

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

Delete an entry from the localStorage

I am attempting to create a basic To-Do list using jQuery, but I have encountered an issue. This is my first time utilizing localStorage. After setting up the structure for my To-Do list, I wanted the items to remain visible when I refresh the page. Initia ...

What is the best way to implement two events in onPress using React Native?

I'm trying to implement the UploadB function and toggle the modal visibility using setModalVisible(!modalVisible)... However, my attempts so far have not been successful. const UploadB = useCallback(() => { dispatch({ type: ADD_P ...

What is the best way to limit the number of items shown in a cart dropdown using JavaScript

I have a shopping cart feature added to my ecommerce web app. Within the header, there is an icon of a cart. When clicked, a dropdown appears showing the items added to the cart. However, if I have 10 items in the cart, the dropdown becomes too lengthy to ...

Using Node.js and Hapi.js alongside Angular.js for web development

Could someone please help me understand how to integrate nodejs (hapi server) with AngularJs? I initially thought that I could intercept all requests made to my Hapi server and handle them using angularjs routes / REST, but it seems like I'm encounter ...

Verify whether the initial value is distinct from the subsequent one using AJAX

I'm currently working on a project where I need to compare the first value received from an AJAX call to the subsequent values. However, I seem to be stuck and unable to figure out how to achieve this. Every 5 seconds, I am checking the follower count ...

A message appeared in the console warning about Vue using canvas-datagrid

Everything is displaying correctly as I intended. However, there is a warning in the console: > vue.js:2 [Vue warn]: Unknown custom element: <canvas-datagrid> - did > you register the component correctly? For recursive components, make > sur ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

The TypeScript compiler is unable to locate the name 'window'

Within my Meteor/React project, I encounter the following line of code: let gameId = window.prompt("Please input the ID of the game you would like to load."); The TypeScript compiler presents an error during transpiling: Cannot find name 'window&apo ...

Using Angular to share JSON data efficiently between controllers

Greetings everyone, I am a beginner in Angular and not very skilled with JavaScript. The issue I'm facing is that although this setup successfully fetches the JSON data, whenever I modify certain object properties, they revert back to their original s ...

Refreshing JqGrid tables after making changes and saving a row

In my PHP file, I have 4 jqGrid tables where I pass a different JSON array for each table. The data displayed on the grids come from one table with various SQL conditions. I am using inline editing for all the grids. After editing and saving a row in tabl ...

Receive alerts in Swift from WKWebView when a particular screen is displayed in HTML

Check out this sample HTML file I have. I'm currently using the WKWebView to display this HTML. My goal is to receive a notification in our Swift code when the user finishes the game and the "high score" screen appears, so we can dismiss the view and ...

Unable to access Form element in Firefox browser

I'm struggling with debugging unfamiliar problems. For instance, in my HTML there's a form: <form name="myForm" > <table> <tr> <td> <input type="radio" name="myType" value="val" onclick="someF ...

Is it possible to upload numerous profiles into the MYSQL database using this WP template?

Apologies in advance if my question is unclear, but in simple terms, I am looking to automate the process of uploading hundreds of profiles and jobs to this WP template: The developer of this template has stated that it is not possible to do this through ...

Using JavaScript, generate table rows and cells

Hey there, I'm struggling with formatting my table correctly within the designated section. Currently, it's printing the rows one below the other instead of creating a 'tr' and multiple 'td' elements for each input field. The ...

Troubles encountered while processing STL file readers

Utilizing STLLoader.js, I am able to render components successfully, however, they all appear with one uniform color which does not resemble real-world components. The image above showcases my implementation in Three.js using STLLoader.js (Binary STL file ...

Tips for securely transmitting data via a hidden form using the POST method

I have a query that displays records of people, and I want to send the id_Persona using a hidden form through a post function to the idsPersonas.php page. However, when I try to do this, it redirects me to an undefined page. Here is the code snippet: < ...

What could be causing the React text input to constantly lose focus with every keystroke?

In my React project using Material-UI library, I have a component called GuestSignup with various input fields. const GuestSignup = (props: GuestSignupProps) => { // Component code goes here } The component receives input props defined by an ...

Utilizing type casting when transmitting data through references

UPDATE: typedef uint16_t UnicodeChar; UPDATE 2: In this particular scenario, it may appear to be not allowed to cast because the sizes of arrays do not match. But then why is it not functioning when, for instance, I am passing a u_array of size 10 (in ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

Material-UI's style is taking precedence over other styles that have been defined

Introduction Last week, I posted a similar query which touched on the same issue. However, as the solution seems to be different this time around, I am revisiting it in a new thread. Check out the updated version of the CodeSanbox Example that reflects t ...