Developing a JSON structure from a series of lists

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"
    ]
];


var newObj = {};

for(i=0; i<data.length; i++){
  //newObj['name'] = data[i][0];
  for(j=1; j<data[i].length;j++){
   newObj[data[i][j+1]] = data[i][j];
   document.write(data[i][j] + "----");
  }
}

document.write(JSON.stringify(newObj));

I am attempting to create a collection of objects where each object includes the "Name" as the initial element of the array, along with the associated value which can be either "ALLOW" or "Deny". For example, I aim to achieve:

{name: "default_PROJECT", connect: "Allow", AddComment: "Allow"} ... etc 

However, there are instances where duplicate keys exist in the arrays, and if the value is Deny, it will always take precedence over a previous Deny value.

I have started by iterating through each array and attempting to set the subsequent element as the key. Am I on the right path?

Answer №1

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"]];


var 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];
    
    console.log('calc', j, key, value);
    

    result[i][key] = value;

    
  }
}

/** IGNORE THIS, IS JUST FOR DEBBUGGING **/
var resultElement = document.getElementById('result1');
var tpl = '';
for(var t = 0, tLen = result.length; t < tLen; t++) {
  var item = result[t];
  
  tpl+= '<table>' +
    '<thead>' +
      '<tr><td colspan="2">' + item.name + '</td></tr>' +
      '<tr><th>KEY</th><th>VAL</th></tr>' +
      '</thead>' +
    '<tbody>'
  ;
  
  for(var key in item) {
    if(!item.hasOwnProperty(key) || key === 'name') { continue; }
    
    tpl += '<tr><td>'+ key +'</td><td>'+ item[key] +'</td></tr>';   
  }
      
  
  tpl += '</tbody></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>


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

Make sure to update the value of a Mongoose document only if it has been

I am looking to update a specific value in the document only if it is newly defined. If the value is not defined, I want to leave it as it is in the document. For example: If this particular document exists in the database: { "_id": "592c53b3bdf350ce00 ...

Is there a way to bypass the "Error: Another application is currently displaying over Chrome" message using Javascript or Typescript?

Can the "Another app is displaying over chrome error" be bypassed using JavaScript or TypeScript? Error Message: https://i.stack.imgur.com/iSEuk.png ...

When combining Socket.io 1.0 with express 4.2, the outcome is a lack of socket connection

According to the title, I am attempting to integrate socket.io 1.0.4 with express 4.2, but all requests with "/?EIO" are resulting in a 404 error. Below are my file configurations: ./bin/www : #!/usr/bin/env node var debug = require('debug')(& ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

What is the best way to retrieve a line of data in JSON format using jQuery?

I am receiving JSON data from a source [{"Title":"Gross Wages","Last":"$40,000","MTD":"$40,000","QTD":"$40,000","YTD":"$40,000"}, {"Title":"Total Taxes","Last":"$50,000","MTD":"$50,000","QTD":"$50,000","YTD":"$50,000"}, {"Title":"Total Benefits","Last":"$ ...

Real-time functionality in React component and Apollo Client is not functioning as expected

I am struggling to develop a user system as it is not working in real-time, causing confusion for me. To illustrate my problem and code, I have set up a sample Sandbox. Please note that this example does not include any validation features and is solely f ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

Steps to incorporate / insert Angular directive in an application

In my app, the main.js file is located in the root folder. -app |_ routes.js |_ main.js -components |_directives |_abc-directive.js I am trying to figure out how to define a directive that can be accessed from a different folder. This is what I at ...

Having difficulty modifying the styling of a paragraph within a div container

I have been working on a function that is supposed to adjust the font-size and text-align properties of a paragraph located within a div tag once a button is pressed. function customizeText() { document.getElementById('centretext').innerHTML = ...

Issue with jQuery fadeTo() not working after appendTo() function completes

I am facing a problem with the code below that is meant to create a carousel effect for my website. The main issue I am encountering is that the original fadeTo() function does not actually fade the elements, but rather waits for the fade time to finish an ...

Choose an element that has been generated dynamically using jQuery

Here is an example HTML table to work with: <table id="#myTable"> <tr id="#row123"><td>Content</td></tr> </table> To insert a new row using jQuery, you can use the following code: $('#myTable').prepend(&ap ...

Issues arise when using res.send() with ExpressJS and Mongoose

Initially, I have multiple callbacks that need to be executed before sending a res.send() to construct a JSON API: app.get('/api', function (req, res){ ... function logPagesId() { console.log("load: " +pagesId); c ...

How can I pass standard HTML as a component in React?

I need help creating a Higher Order Component (HOC) that accepts a wrapper component, but allows me to pass standard HTML elements as inner content. Here is an example of what I want to achieve: type TextLike = string | {type,content} const TextLikeRender ...

Tips for resolving a flickering issue that occurs when switching to an input field with our default value / placeholder plugin

In the realm of web development, numerous plugins cater to the implementation of HTML5's placeholder attribute in older browsers. The plugin we have opted for can be found here. Unlike some other alternatives, this particular plugin, with a few modif ...

What are the steps to ensure that data retrieved from an API is accurately displayed in a table?

My current goal is to collect data from the crypto compare API and display it in a table format. Although I am able to generate the necessary elements and append them to the table body, I am facing an unusual issue. Each time I use a for loop to iterate th ...

What is the best method for ensuring that cheese rises to the top?

Is there a way to increase the value of the variable cheese? I suspect it has something to do with how the variable cheese is defined each time the JavaScript is activated, but I'm not sure how to go about it. Can you offer some guidance on this? & ...

Error: The function $(...).maxlength is not recognized - error in the maxlength plugin counter

I have been attempting to implement the JQuery maxlength() function in a <textarea>, but I keep encountering an error in the firefox console. This is the code snippet: <script type="text/JavaScript"> $(function () { // some jquery ...

Developing a RESTful web application on Android with the Zend Framework

I have developed a web application using the Zend Framework (Version 1.11.11) and now I want to utilize the same backend code for creating the mobile version of this app (specifically for Android). My goal is to receive responses in XML and JSON format for ...

Utilizing a function as an argument in another function (with specified parameters)

I’m stuck and can’t seem to solve this problem. In my function, the parameter filter needs to be a function call that accepts an object created within the same function: function bindSlider(time, filter) { var values = { min : 8, max : ...

Is there a way to retrieve the value of bindings in the component controller using Angular 1.5 and Typescript?

In my quest to develop a versatile left-hand menu component that can dynamically display different menu structures based on input strings, I stumbled upon an interesting challenge. By binding a string to the <left-hand-menu-component> element like so ...