Is it possible to combine two HTML tables by using JavaScript Objects as the source of data?

I have an array containing multiple arrays, and I want to create objects from each sub-array and then combine them into a single table. While I've been able to accomplish this, I'm looking for assistance on how to use these objects to create one large table.

If a key exists in one object but not in the others, the value can simply be left blank for the object that lacks the key. I know how to create separate tables, but I'm unsure of how to merge them into a single larger table.

var data  =[["default_PROJECT","Allow","Connect","Allow","AddComment","Allow","Write",
"Allow","ViewComments","Allow","ExportData","Allow","ExportImage","Allow","ViewUnderlyingData","Allow","Read","Allow","ShareView","Allow","Filter"],
["Allow","ExportImage","Allow","Write","Allow","ViewComments",
"Allow","ShareView","Allow","Filter","Allow","ExportData","Allow","Connect","Allow",
"Read","Allow","ViewUnderlyingData","Allow","AddComment","Allow","ViewComments","Deny","ExportData","Allow",
"AddComment","Deny","Write","Allow","Read","Deny","ExportXml","Deny","ShareView","Allow","Connect","Allow","ChangeHierarchy","Allow",
"WebAuthoring","Deny","ViewUnderlyingData","Deny","Filter","Deny","ExportImage"]];  
   // The rest of the JavaScript code remains unchanged
    


http://jsfiddle.net/h2s17hac/

Answer №1

This code snippet combines information from two tables.

Link to Code

var data  =[["default_PROJECT","Allow","Connect","Allow","AddComment","Allow","Write",
"Allow","ViewComments","Allow","ExportData","Allow","ExportImage","Allow","ViewUnderlyingData","Allow","Read","Allow","ShareView","Allow","Filter"],
["test_PROJECT", "Allow","ExportImage","Allow","Write","Allow","ViewComments",
"Allow","ShareView","Allow","Filter","Allow","ExportData","Allow","Connect","Allow",
"Read","Allow","ViewUnderlyingData","Allow","AddComment","Allow","ViewComments","Deny","ExportData","Allow",
"AddComment","Deny","Write","Allow","Read","Deny","ExportXml","Deny","ShareView","Allow","Connect","Allow","ChangeHierarchy","Allow",
"WebAuthoring","Deny","ViewUnderlyingData","Deny","Filter","Deny","ExportImage"]];

function makeObjects(data){
    result = [];
     for(var i = 0, len = data.length; i < len; i++) {
   var list = data[i];
   result[i] = { Name: list[0] };
  for (var j = list.length - 1; j >= 1; j = j - 2) {
     var key = list[j];
     var value = list[j - 1];
     if( result[i][key] !== "Deny" ) {
         result[i][key] = value;
     }
 }
}
    return result;
}

function sortObject(obj) {
    return Object.keys(obj).sort().reduce(function (result, key) {
        result[key] = obj[key];
        return result;
    }, {});
}

function getKeys(data){
    var keys = [];
   for(i=0; i<data.length; i++){
       key = Object.keys(data[i]);
      for(j =0; j<key.length; j++){
          if(keys.indexOf(key[j]) == -1){
           keys.push(key[j]);   
          }
       }
   }
    return keys;
}

function addMissingKeys(keys, data){
    var filtData = [];
    for(i=0; i<data.length; i++){
        for(j=0; j<keys.length; j++){
         if(data[i][keys[j]] == undefined){
          data[i][keys[j]] = "";  
         }
        }
    }
    for(num=0; num<data.length; num++){
        filtData.push(sortObject(data[num]));
    }
return filtData;
}

var dataa = makeObjects(data);
var keys = getKeys(dataa);
var filtData = addMissingKeys(keys, dataa);
console.log(filtData);
 var resultElement = document.getElementById('result1');
 var tpl = '<table align=center style="width:75%;">';
 for(var t = 0, tLen = filtData.length; t < tLen; t++) {
   var item = filtData[t];
                 
   tpl+= '<tr><td>' + item.Name + '</td>';
   
   for(var key in item) {
     if(!item.hasOwnProperty(key) || key === 'Name') { continue; }
                   if(item[key] != "") {
                     if(item[key] == "Allow"){
                         tpl += '<td style="background-color:greenyellow;">'+ key +':<br>'+ item[key] +'</td>';   
                     }
                     else{
                         tpl += '<td style="background-color:red;">'+ key +':<br>'+ item[key] +'</td>';   
                     }
                   } else {
                   tpl += '<td></td>';
                   }
                 
   }
               tpl += '</tr>';
 }
             tpl += '</table>';
 resultElement.innerHTML = tpl;
table { text-align: left; width: 100%; margin-bottom: 50px; border-collapse: collapse;}
td, th { width: 50%; border: 1px solid black; line-height: 1; padding:2px 10px;}
[colspan="2"] { color: blue; font-weight: bolder;text-transform: uppercase; text-align: center;}
<div id="result1"></div>
<div id="test"></div>

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

Php/JavaScript Error: Identifier Not Found

I've double-checked my code multiple times, but it still doesn't seem to be working properly. When the PHP runs, the browser console displays the following error: Uncaught SyntaxError: Unexpected identifier. I'm not sure if this is a si ...

Can Metro style apps be used on iPhone and iPad devices as well as in web applications?

I'm curious to know if I can create a single metro style app using HTML5 and Javascript that will be compatible with both iPhone and iPad? Any assistance would be greatly appreciated! ...

Troubleshooting Vue v-for loop triggering click events on multiple items simultaneously

After conducting a thorough search, I haven't found a suitable answer for my issue. The problem I am facing involves a v-for loop with buttons on each item, using VueClipboard2 to copy text. Whenever a button is clicked, some CSS changes are applied t ...

Utilizing Node.js to create macOS wrappers (such as .pkg and .app files)

Seeking guidance on packaging my Node.js application for macOS as a .pkg or .app file. Any recommendations on the most efficient method to accomplish this task? Any useful tutorials or tools would be greatly appreciated. Thank you, Asaf ...

At a specific point in the route, all CSS and JS links in Node.js vanish

Hey everyone, I'm facing a strange issue where the CSS styling and JS code are not loading when I access the route http://localhost:5000/posts/edit/<%=idofblog%>. As a result, my webpage looks very unattractive, and I'm not sure what's ...

When attempting to create text with Three.js using the TextBufferGeometry method, an error arises indicating that the property yMax is unreadable due

While trying to add text to a three.js scene, I encountered the error message "Uncaught TypeError: Cannot read property 'yMax' of undefined". let loader = new THREE.FontLoader(); let font = loader.parse( jsonFont ); let geometry = new THRE ...

Using AJAX to upload an image and passing multiple parameters

I'm facing an issue when trying to upload an image along with other input text in a form and send it to ajax_php_file.php. Whenever I upload the image, all my input text fields appear empty. Any assistance would be greatly appreciated. Thank you very ...

Retrieve a specific string located within a <div> element by utilizing XPath

Below is the structure of the HTML I am working with: <div class = "something" > <div> <span>Some text</span> </div> "Automated Script" </div> Currently, I am using Selenium Webdriver for testing and ne ...

What is the proper method for interpreting binary floating-point data when utilizing XMLHttpRequest?

I am attempting to load a binary file containing floating-point values into an array using JavaScript. Here is my current method: var mRequest = new XMLHttpRequest(); mRequest.open('GET', 'res/binary_float_data.bin'); mRequest.response ...

Tips for implementing pagination in the frontend (specifically Angular) with a pre-defined limit from the backend (NodeJS, TypeORM)

Exploring Angular and NodeJS for the first time, I am eager to implement pagination in my frontend listing. While I have successfully limited entries in my backend method, I am facing challenges in integrating it into my frontend code and unsure how to pro ...

Struggling to display page numbers within a Bootstrap table

I am currently working on implementing pagination using the resource found here: Here is a snippet of my code: http://jsfiddle.net/bb0y3vg9/1 Progress So Far: The data retrieved from the backend is successfully populating the table. Challenges Faced: ...

What is the best way to position two programmatically created divs next to each other on a webpage

Is there a way to place two divs next to each other? And how can I do the same for multiple divs at once? Unlike canvas elements, divs don't automatically align side by side. Also, why isn't the button's value changing the text displayed on ...

Issue with aligning the image product in Bootstrap 4

I'm currently working on creating a basic online shopping page for my PHP training, and I've run into a bit of a roadblock with the HTML portion. Even after using Bootstrap, I'm still struggling to simplify things. When I view the result of ...

How do you remove a section of an element's box model?

Query: I am trying to achieve a half circle effect by removing a portion of the circle element's box model. Can this be done and if so, how can I accomplish it? Creating complex shapes would become much easier with this functionality. Strategy: To ...

Determining the margin-left value of a centrally positioned table

I have a table with variable columns, meaning the columns of the table are dynamic. The number of columns will keep changing, causing the table to be centralized and the margin-left value to adjust accordingly. Now, I need to calculate the margin-left val ...

Enhancing the visual appeal of Struts 2 with property tag styling

Utilizing the Struts2 property tag to fetch the user's name, my code looks like this. <div class="MyStyle"> <p> Hi! <s:property value="#session.firstName"/></p> </div> However, I am facing an issue wh ...

Make the Angular Modal scrollable except for when a specific div is being click dragged

I am working on an Ionic app that uses AngularJS. One issue I encountered is with a modal popup that can sometimes extend beyond the visible area. To address this, we applied overflow: hidden to its CSS class. However, there is a specific functionality i ...

The problem I am facing is with the React Ant d Modal Component, where I am unable to render the

Hey there! I'm currently working with React Js and the 'Ant design Modal Component'. When I click on a button, the modal should open and display the content of each user with their unique ID. However, I'm facing an issue where all modal ...

Creating a cooldown feature for individual users across all commands in Discord.js

What should I do if a user is spamming my commands and I want all commands to have the same cooldown for that specific user? Below is my current code: if (talkedRecently.has(msg.author.id)) { msg.channel.send("Wait before getting typing t ...

Pulling data from a MySQL database using AJAX and PHP to convert it into a JavaScript variable, resulting in

I am attempting to retrieve MySQL data using PHP, convert it to JSON, and then pass it into my JS variables for Chart.js. The JSON generated by PHP appears correct. However, when trying to access the data within my variables, the console is displaying them ...