Arranging a collection of objects into a two-dimensional array

I've got an array of objects that I want to format in a way suitable for react-csv, specifically as a 2D array resembling a nested loop structure shown below:

https://i.sstatic.net/41cuj.png

The desired end result should look like this:

[
  ["Name", "Message", "Column", "configDataType","dbDataType"],
  ["STAGE", "Columns present in source config but not in the database.", "TEST", "", ""],
  ["", "", "TEST1", "", ""],
  ["", "", "TEST2", "", ""],
  ["", "Columns present in database but not in the source config.", "", "", ""],
  ["", "Columns with datatype mismatch.", "LAST_NAME", "varchar(50)", "varchar(40)"],
  ["", "", "FIRST_NAME", "varchar(50)", "varchar(40)"],
  ["RAW", "Column sets are identical.", "", "", ""],
  ["LAST", "Column sets are identical.", "", "", ""],
  ["HIST", "Column sets are identical.", "", "", ""],
  ["CORE", "Column sets are identical.", "", "", ""],
  ["ADDR", "Column sets are identical.", "", "", ""],
  ["CONFIG", "Column sets are identical.", "", "", ""],
  ["ACTION", "Column sets are identical.", "", "", ""]
]

Although I have made some progress so far, I haven't been able to achieve the intended outcome. Any guidance on what might be missing would be greatly appreciated.

const data = {
  // Object data content goes here
}

const res = _.flattenDeep(Object.keys(data).map(i => {
  return data[i].map(j => {
    return {
      ...j,
      tableName: i
    }
  })
}))

console.log(res.map(i => {
  return [
    i.tableName,
    i.message,
    ...((i.columns.length > 0 ? i.columns : i.columnsName).map(j => typeof j === 'string' ? j : j.name)),
    ..._.compact(((i.columns.length > 0 ? i.columns : i.columnsName).map(j => typeof j === 'string' ? '' : j.configDatatype)),
    ...(((i.columns.length > 0 ? i.columns : i.columnsName).map(j => typeof j === 'string' ? '' : j.dbDatatype))
  ]
}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

Answer №1

Why should we avoid using old-fashioned imperative code? Consider this alternative approach:

const data = {
  "STAGE": [{
      "infoLevel": "error",
      "message": "Columns present in source config but not in the database.",
      "columns": [],
      "columnsName": [
        "TEST",
        "Arun",
        "Abnc"
      ],
      "type": "String"
    },
    {
      "infoLevel": "error",
      "message": "Columns present in database but not in the source config.",
      "columns": [],
      "columnsName": [],
      "type": "String"
    },
    {
      "infoLevel": "error",
      "message": "Columns with datatype mismatch.",
      "columns": [{
        "name": "LAST_NAME",
        "configDatatype": "varchar(50)",
        "dbDatatype": "varchar(40)"
      }, {
        "name": "FIRST_NAME",
        "configDatatype": "varchar(50)",
        "dbDatatype": "varchar(40)"
      }],
      "columnsName": [],
      "type": "Table"
    }
  ],
  // more data here...
};

var rows = [];
for (var c1 in data) {
  const list = data[c1];
  for (var i in list) {
    const obj = list[i];
    var c2 = obj.message;
    for (var j in obj.columnsName) {
      rows.push([c1, c2, obj.columnsName[j]]);
      c1 = ""; c2 = "";
    }
    for (var j in obj.columns) {
      const col = obj.columns[j];
      rows.push([c1, c2, col.name, col.configDatatype, col.dbDatatype]);
      c1 = ""; c2 = "";
    }
    if (c2 != "") rows.push([c1, c2]);
    c1 = "";
  }
}

console.log(rows);

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

Switching over the database for a session away from using ajax

I am currently working with an XML API that interacts with a database. My website utilizes the functions of this XML API to retrieve data from the database. I am facing a challenge where I need to update the database based on the user's selection on t ...

What is the best way to dynamically insert an email value into a JSON file?

Here is the structure of my JSON file: test.json: { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3b8a1baa093beb2babfbabdb2a7bca1fdb0bcbe">[email protected]</a>", "password": "Sanju@143", ...

Exploring the power of Next.js dynamic routes connected to a Firestore collection

Currently seeking a solution to create a dynamic route that will display each document in a Firestore collection using Server-side Rendering. For instance, if there is a document named foo, it would be accessible at test.com/foo under the [doc] page compo ...

Enhanced functionality for Thingworx using ThreeJS

I'm currently facing an issue while developing a 3 JS extension for Thingworx, specifically with the renderHtml function when working with a 3 JS canvas (Check out the code). //runtime.ts file renderHtml(): string { let htmlString = '<div ...

Using for loops in Vue.js to dynamically generate HTML elements

I have a JSON object passed into an EJS template, and I want to achieve the same table structure in VUE.js. However, it seems like v-for in Vue only works with li tags. Is there a way to create a similar loop in VUE that generates HTML elements like show ...

Guide on decoding JSON file generated from curl in PHP

After executing my cURL request, the following code is executed: $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } The respons ...

Playing sound files on Angular using Howler.JS

I am currently trying to incorporate the ability to play an mp3 file within a Cordova + Ionic hybrid app. The sound file is located at: www/sounds/dubstep/sound.mp3 I am attempting to play the file from a service placed in /www/scripts/services/global.j ...

A comprehensive guide on using ajax to reproduce a Postman POST API request

Currently, I am able to retrieve an "access_token" using Postman; however, I am attempting to recreate this process in ajax for experimentation purposes on jsfiddle. In Postman, the following setup is used: A POST request URL: No active headers Body in ...

"Effortlessly rearrange and remove specific elements using jQuery UI's drag-and-drop

Hello everyone, I have designed a simple interface with 3 different "zones". The first zone contains a list of elements that the user possesses, the second zone allows the user to drag and sort these elements, and the third zone enables the user to delete ...

If you scroll quickly, watch out for the flickering of the fadeIn and fadeOut

I have a script that fades in an element once the user scrolls more than 145px from the top of the page. $(window).scroll(function(){ if ($(this).scrollTop() > 145) { $('#fademenu').fadeIn(); } else { $('#fademenu').fadeOut(); } } ...

Sending AJAX request within a Twitter Bootstrap modal in Symfony2

After exhausting countless Google and StackOverflow search results, I have come to the conclusion that seeking help is my best option. I am currently developing a Symfony2 application. In every view of my app, I have integrated a Twitter Bootstrap modal e ...

Sleek transitions for navigating between cells in a data table

I am looking to implement a smooth animation for cell navigation. Check out what I currently have: http://jsfiddle.net/0ardb3u0/ When the mouse hovers over a cell, I want the full column and row of that cell to be selected and highlighted in blue. How ...

Scaling down the screen for a smaller display

Having trouble achieving a specific effect and could use some assistance. My goal is to create an action where, upon clicking on the nav element (for simplicity, I've set it to be triggered by clicking anywhere on the body), the following should occur ...

Issue with visibility of pagination in AngularJS ui

I am facing an issue with pagination in my AngularJS UI application. I have a dataset that requires server-driven pagination due to its size. The problem I'm encountering is that the pagination element is not displaying on the page, even though I hav ...

Is there a conflict between bootstrap.min.JS and chart.min.js?

I have been working on developing an admin page for customer support and I recently added a visually appealing chart to display some data on the home screen. The chart integration was successful, but when I introduced tab panes to the page and refreshed ...

Obtaining the initial variable from an array - a simple guide

Although it seems simple, I am having trouble getting it to work. I have an array with 2 variables inside that I retrieve from jQuery. var features = [long, lat ] I want to iterate through all the values in the loop and use: fetures[i] This should give ...

Tips for showcasing Markdown files within subdirectories in Next.JS

In my Next.JS project, I am managing numerous Markdown files that are organized into various category folders. For example, I have folders named 'CategoryOne' and 'CategoryTwo' located at the root level of the project alongside node_mod ...

Is it possible to update the useContext value within a child component so that all other child components can access the updated value?

Is there a way to set a default value (like null) in a parent context and then change that value in a child component so other children can access the updated value? For example, imagine we have an App.jsx file where a userContext is created and passed do ...

Incorporate a smooth transition effect to a dynamically resizing div button

In my current setup, I have 3 buttons that can toggle between different visible divs. In the future, I may add more buttons to switch between additional divs. At the moment, the first div is active (display set to block), while all other divs are hidden ( ...

Utilizing Treant.js within a Vue.js application

After attempting to integrate the Treant.js library into my Vue app for creating a tree diagram from JSON data, I encountered some errors. In my main view, here are the import statements... import Vue from "vue" import store from "../../store" import { ge ...