What is the process for generating a new array of objects by leveraging the contents of two given arrays?

In my data collection, I have multiple objects stored in arrays like so:

tableCols = [
    {
        "id": 50883,
        "header": "ABC",
        "operator": "Sum",
        "order": 2
    },
    {
        "id": 50884,
        "header": "Leakage",
        "operator": "Sum",
        "order": 3
    },
     .....
]

Additionally, there is another dataset with its own array of objects:

dataArr = [
    {
        "id": 925095,
        "grid_row_id": 170712,
        "grid_col_id": 50883,
        "data": "10",
        "error_msg": null,
        "locked": 1
    },
    {
        "id": 926137,
        "grid_row_id": 170712,
        "grid_col_id": 50884,
        "data": "34",
        "error_msg": null,
        "locked": 1
    },
    {
        "id": 926137,
        "grid_row_id": 170713,
        "grid_col_id": 50883,
        "data": "22",
        "error_msg": null,
        "locked": 1
    },
    {
        "id": 926137,
        "grid_row_id": 170713,
        "grid_col_id": 50884,
        "data": "100",
        "error_msg": null,
        "locked": 1
    },
    .....
]

It is noteworthy that each grid_col_id in the second array corresponds to an id in the first array.

The goal is to create a new array structured as follows:

formattedData = [
    {
        "ABC": 10,
        "Leakage": 34,
        ....
    },
    {
        "ABC": 22,
        "Leakage": 100,
        ....
    },
    ....
]

This involves iterating through dataArr, grouping objects by grid_row_id, and generating key-value pairs where the key matches the header in tableCols based on grid_col_id = id.

For instance, using the provided dataArr example, with grid_row_ids 170712 and 170713, we can extract the ABC and Leakage values accordingly:

"ABC": 10,

The current implementation generates a new object for each item in dataArray instead of filtering through to create a new object per row. The existing code snippet looks somewhat like this:

        let ogGrid = [];
        let formattedData = [];
        let newObj = {};

        dataArr.forEach(row => {
                tableCols.forEach(element => {
                    if(row.grid_col_id === element.id)
                        newObj[element.header] = Number(row.data);
                });
            })
            ogGrid = {...newObj};
            formattedData.push(ogGrid);
        });

To achieve the desired structure, what modifications should be made?

Answer №1

One approach is to establish a mapping system where a column id corresponds to a header name, and another map links a row id to an empty object initially. Utilize these mappings to fill the objects while traversing through the data. Eventually, compile all objects into an array.

const tableCols = [{"id": 50883,"header": "ABC","operator": "Sum","order": 2},{"id": 50884,"header": "Leakage","operator": "Sum","order": 3},];
const dataArr = [{"id": 925095,"grid_row_id": 170712,"grid_col_id": 50883,"data": "10","error_msg": null,"locked": 1},{"id": 926137,"grid_row_id": 170712,"grid_col_id": 50884,"data": "34","error_msg": null,"locked": 1},{"id": 926137,"grid_row_id": 170713,"grid_col_id": 50883,"data": "22","error_msg": null,"locked": 1},{"id": 926137,"grid_row_id": 170713,"grid_col_id": 50884,"data": "100","error_msg": null,"locked": 1},];

const headerMap = new Map(tableCols.map(({id, header}) => [id, header]));
const rowMap = new Map(dataArr.map(({grid_row_id}) => [grid_row_id, {}]));
for (const {grid_row_id, grid_col_id, data} of dataArr) {
    rowMap.get(grid_row_id)[headerMap.get(grid_col_id)] = +data;
}
const data = [...rowMap.values()];

console.log(data)

Answer №2

let originalGrid = {};
let formattedDataArray = [];
let newObject = {};

dataArr.forEach(row => {
  if (!originalGrid[row.grid_row_id]) {
    originalGrid[row.grid_row_id] = {};
  }

  tableCols.forEach(element => {
    if (row.grid_col_id === element.id) {
      originalGrid[row.grid_row_id][element.header] = Number(row.data);
    }
  });
});

for (let id in originalGrid) {
  formattedDataArray.push(originalGrid[id]);
}

console.log(formattedDataArray);
<script>
  const tableCols = [{
      "id": 50883,
      "header": "ABC",
      "operator": "Sum",
      "order": 2
    },
    {
      "id": 50884,
      "header": "Leakage",
      "operator": "Sum",
      "order": 3
    }
  ]

  const dataArr = [{
      "id": 925095,
      "grid_row_id": 170712,
      "grid_col_id": 50883,
      "data": "10",
      "error_msg": null,
      "locked": 1
    },
    {
      "id": 926137,
      "grid_row_id": 170712,
      "grid_col_id": 50884,
      "data": "34",
      "error_msg": null,
      "locked": 1
    },
    {
      "id": 926137,
      "grid_row_id": 170713,
      "grid_col_id": 50883,
      "data": "22",
      "error_msg": null,
      "locked": 1
    },
    {
      "id": 926137,
      "grid_row_id": 170713,
      "grid_col_id": 50884,
      "data": "100",
      "error_msg": null,
      "locked": 1
    }
  ]
</script>

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

Transform a dictionary of bytes into JSON format

I've encountered an issue trying to convert a bytes dictionary returned from an API into JSON format, but so far I haven't been successful. Here is a snippet of the sample data: >>> endpoint_req.content b'{\n "ERSEndPoint" : ...

The issue of array sorting, specifically the function(a, b) {return b.value - a.value), is causing some

I am struggling to retrieve data from firebase and sort them according to the field 'overallScore' in descending order. Despite following suggestions like using array.sort(function(a, b) {return b.value - a.value), I have not been successful in s ...

Modify the background color of a div by selecting a hex code from a dropdown menu

Is there a way to utilize jQuery in order to alter the background of a <div> by choosing the HEX code from a separate dropdown menu? HTML <select id="target"> <option value="#c2c2c2">Grey</option> <option value="blue">Bl ...

What is the best way to interact with Redis without using any external modules?

I am curious about the communication process between the node redis wrapper and the RESP (REdis Serialization Protocol) database. Here is a simple example: const redis = function(uri) { this.client = '' // How do we establish a connection wit ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

Use Node.js with Selenium and WebdriverIO to simulate the ENTER keypress action on

I have put in a lot of effort trying to find the solution before resorting to asking this question, but unfortunately I have not been successful. All I need to know is how to send special characters (such as the enter key and backspace) with Node.js using ...

Using AngularJS ui-router ui-sref results in the error message "Uncaught TypeError: Cannot read property '0' of undefined."

I am currently working on an angularJS component that utilizes ui-router with 2 straightforward route states. export default function Routes($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('details', { ...

removing the mapStateToProps function will result in an undefined value

I am new to React and I'm in the process of converting a class component to functional components using hooks. I need some guidance on safely removing 'mapStateToProps' without encountering undefined errors. I have two pages, A.js and B.js. ...

Create a full-width slider using Materialize CSS framework

When using materializecss to create a slider, I encountered an issue where the image is full width but not full height, causing scrollbars to appear. What changes can I make to ensure the slider fills out my screen without any scrollbars? Additionally, I ...

The functionality of angular-ui's ui-utils and ui-scroll module is currently nonfunctional in version 0.1.0

I have been trying to implement the features from this Angular UI library: http://angular-ui.github.io/ui-utils/, particularly focusing on this aspect: https://github.com/angular-ui/ui-utils/blob/master/modules/scroll/README.md Unfortunately, despite my e ...

Using Node.js and Express to import a simple JavaScript file as a router

Can anyone help me understand how to import the user.json json file into my user.js? I want the json file to be displayed when typing /user but I'm struggling with the new version of Node. index.js import express from 'express'; import body ...

How can we efficiently loop through all the icons in React Material-UI?

I am looking to iterate over all the icons from @material-ui/icons in a React application. If I want to import a single icon, I can do so like this import IconNameIcon from '@material-ui/icons/IconName' and then use it in my component like th ...

Using querySelector() to target specific divs by their classes while excluding any other classes

I am attempting to retrieve only the first divs while excluding the second ones: <div class="_5pcr userContentWrapper"> <div class="_5pcr userContentWrapper _4nef"> After researching, I discovered that the querySelector function should be abl ...

Dreamweaver restricts my ability to utilize JavaScript for coding

My JavaScript isn't working in Dreamweaver. I have linked the script file correctly using the given code: <script src="file:///C:/Users/Matthew/Desktop/Untitled-2.js" type="text/script"></script> However, when I try to call it with scrip ...

Fill the angular ui-bootstrap popover with content

Can anyone help me with populating an angular ui bootstrap popover? My goal is to populate the popover with a collection of actor names. Below is the code snippet: <div class="container" ng-if="radioModel=='Search for Actor'"> <p> ...

Connecting a dynamically assessed function on the $scope to a service

Within my code, there is a function called make_value_summary that has the capability to generate a generic summary of various fields within the $scope. By applying this function, I am able to create location_summary, which is then linked to the view using ...

Dynamic updating of scores using Ajax from user input

My goal is to design a form that includes three "Likert Scale" input fields. Each of these three inputs will have a total of 10 points that can be distributed among them. The submit button should become enabled when the score reaches 0, allowing users to s ...

Tips for correctly loading all elements on an HTML page before making CSS modifications

This question has been asked several times in the past. I am asking because when I used the on ready callback in jQuery, it did not change the placeholder text of my element "search_input". $( document ).ready(function() { $("#search_input").attr(' ...

Is there a way to connect and interact with a different ng-controller's ng-model within a separate ng-controller?

Is it possible to access the ng-model from another ng-controller and if so, how can it be done? In this scenario, I am using two controllers. The first controller has a model called mddl1, while the second controller does not have any other model. However, ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...