Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript?

   // Necessary input

columnHeaders=['deviceName','Expected','Actual','Lost']
machine=['machine 1','machine 2','machine 3','machine 4','machine 5']
data=[
    {expectedData:[600,400,500,200,100],label:'Expected'},
    {actualData:[500,300,400,100,50],label:'Actual'},
    {LostData:[100,100,100,100,50],label:'Lost'}
]

// Desired output

tableData=[
{deviceName:"machine 1",Expected:600,Actual:500,Lost:100},
{deviceName:"machine 2",Expected:400,Actual:300,Lost:100},
{deviceName:"machine 3",Expected:500,Actual:400,Lost:100},
{deviceName:"machine 4",Expected:200,Actual:100,Lost:100},
{deviceName:"machine 5",Expected:100,Actual:50,Lost:50} ]

I attempted to use hardcoded keys, but seeking a more generic solution. Can anyone assist with this problem?

//Attempted solution
   let array=[];let obj={};
for(let i=0;i<machine.length;i++){
        var expected = data[0].expectedData[i];
        var actual = data[1].actualData[i];
        var lost = data[2].LostData[i];
    obj ={[columnHeaders[0]]:machine[i],[columnHeaders[1]]:expected,[columnHeaders[2]]:actual,[columnHeaders[3]]:lost}
    console.log(obj);
    array.push(obj);
}
console.log(array);

Answer №1

To optimize the array, consider utilizing a more efficient format with consistent keys for the value arrays.

Start by converting the machine array into an array of objects with a single property. This new array will serve as the initial value for reducing the data array, which could potentially be simplified to a single array consisting solely of objects without nested structures.

var columnHeaders = ['deviceName', 'Expected', 'Actual', 'Lost'],
    machine = ['machine 1', 'machine 2', 'machine 3', 'machine 4', 'machine 5'],
    data = [{ expectedData: [600, 400, 500, 200, 100], label: 'Expected' }, { actualData: [500, 300, 400, 100, 50], label: 'Actual' }, { LostData: [100, 100, 100, 100, 50], label: 'Lost' }],
    result = data.reduce(
        (r, { label, ...o }) => Object.values(o)[0].map((v, i) => ({ ...(r[i] || {}), [label]: v })),
        machine.map(v => ({ [columnHeaders[0]]: v }))
);

console.log(result);

Answer №2

While it may not be the most optimal solution, you could experiment with the following code for your data:

let columnHeaders=['deviceName','Expected','Actual','Lost']
let machine=['machine 1','machine 2','machine 3','machine 4','machine 5']
let data=[
    {expectedData:[600,400,500,200,100],label:'Expected'},
    {actualData:[500,300,400,100,50],label:'Actual'},
    {LostData:[100,100,100,100,50],label:'Lost'}
]

let tableData = machine.reduce((acc, item, key)=>{

        acc.push({
            [columnHeaders[0]]: item,
            [columnHeaders[1]]:data[0].expectedData[key],
            [columnHeaders[2]]:data[1].actualData[key],
            [columnHeaders[3]]:data[2].LostData[key],
        })

        return acc
}, [])


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

What is the method for obtaining an element with a class name that does not match a specific value?

I'm trying to figure out how to select an element with a class name that is different from the value passed in. For example: $(document).ready(function () { $(document).on('change', '#allRolesDD', function () { var toS ...

The code functions properly within the emulator, however, it fails to execute on an actual device

Yesterday, I posted a question about the background related to this topic: on click event inside pageinit only works after page refresh. I received an answer for my question and tested it in Chrome devtools where it worked perfectly. However, today when ...

Encountered an issue while attempting to start the JavaScript debug adapter in Visual Studio

When attempting to debug my script code in Visual Studio, I encountered an error. How can I resolve this issue? ...

I am attempting to input the form data, but all I see on the console is "null" being printed

I am facing an issue where the console.log(data) statement is printing null on the console. I am trying to send the form data (with id "myform") to a Java backend post method, but for some reason the code is not functioning correctly. Can anyone identify ...

Setting a value programmatically in a Material-UI Autocomplete TextField

In my React application, I am using material-ui Autocomplete and TextField components to allow users to select values from a dropdown list. However, I am looking for a way to programmatically set the input value by clicking a button, without having to choo ...

What is the best way to compare and identify the variances between two JSON documents in Marklogic using JavaScript?

Is there a way to analyze and compare two JSON documents in Marklogic using JavaScript to identify any differences between them? ...

Dynamic Divider for Side-by-Side Menu - with a unique spin

I recently came across a question about creating responsive separators for horizontal lists on Stack Overflow While attempting to implement this, I encountered some challenges. document.onkeydown = function(event) { var actionBox = document.getElementB ...

Utilize the findIndex method to search for an element starting at a designated index

Below is a snippet of code that I have: private getNextFakeLinePosition(startPosition: number): number{ return this.models.findIndex(m => m.fakeObject); } This function is designed to return the index of the first element in the array that has ...

The library path in a react (js) integrated mono repo could not be resolved by Nx 16

Greetings everyone, I am a newcomer to the world of NX Monorepo. Following the step-by-step instructions on how to create an Integrated React Monorepo from the official NX website can be found here. I diligently followed each instruction provided. Howeve ...

Error: User cannot be used as a constructor

When attempting to register a user using a Node.js app and MongoDB, I encountered the following error message: const utente = new Utente({ ||||| TypeError: Utente is not a constructor This is my model file, utente.js: const mongoose = require("mongoose") ...

What is the best way to send pg-promise's result back to the controller in Express?

While working with Ruby on Rails (RoR), I am familiar with the MVC (Model-View-Controller) concept. In this framework, the controller is responsible for receiving data from the model, processing it, and rendering the view. An example of this structure look ...

Leveraging RXJS for efficient data retrieval in nodejs

When dealing with sending a bulk of data and moving on to the next one upon completion, it can be quite challenging. Take for instance this function: async function test() { await sample.sampleStructure() await sample.sampleDataAdd() await sample.sa ...

Issue with form validation causing state value to remain stagnant

Giving my code a closer look, here is a snippet in HTML: <input type="text" name="email" id="email" autoComplete="email" onChange={(e) => {validateField(e.target)}} className="mt-1 ...

What is the reason for injecting a service into 2 modules following the Singleton Pattern?

Here is the current file situation: AppService AppModule AModule AComponent BModule BComponent Regarding the Service, I have noticed that Angular will create two separate instances of the service if it is injected into two compone ...

Storing the array with the highest length in a temporary array using Javascript

I am currently working with two arrays that can be of equal length or one may be longer than the other. My goal is to determine the longest array if they are not equal in length, and then use this length to control a loop. $.ajax({ url: "/static/Dat ...

Leveraging Javascript within Objective-C

Can you help me understand how to implement this JavaScript code in Objective-C? var theFormId = $('form').filter(function() { return this.innerHTML.indexOf('forgot your password') != -1; }).attr('id'); Is there a way to int ...

Unable to open javascript dialog box

One issue I encountered involves a jqGrid where users have to click a button in order to apply any row edits. This button is supposed to trigger a dialog box, which will then initiate an ajax call based on the selected option. The problem lies in the fact ...

Definitions for nested directories within a main index.d.ts

We have developed custom typings for the latest version of material-ui@next and successfully included them in the library during the last beta release. For those interested, you can access the index.d.ts file here. However, there seems to be a problem wi ...

Issue encountered during Node.js installation

Every time I attempt to install node js, I encounter the following errors: C:\Users\Administrator>cd C:/xampp/htdocs/chat C:\xampp\htdocs\chat>npm install npm WARN package.json <a href="/cdn-cgi/l/email-protection" class ...

Locating the save directory with fileSystem API

I've been working on saving a file using the fileSystem API. It appears that the code below is functional. However, I am unable to locate where the saved file is stored. If it's on MacOS, shouldn't it be in this directory? /Users/USERNAM ...