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

There seems to be an issue with npm displaying an inaccurate version number for my

In brief: The version of my module on npmjs.org doesn't match the version in package.json. Why? I have a JavaScript module that I released on npm and bower: https://github.com/Offirmo/network-constants.js It has a package.json for npm and a bower.js ...

Dividing a fixed string state according to an increment state and showcasing the state in a React component

I'm facing an issue with my code structure, which can be found here: CodeSandbox The problem lies within the useGenText() hook that generates words every nth second in a read-only format, meaning it cannot be modified. Additionally, there is the useL ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...

Bypassing the "Your connection is not private" error in NodeJS + Express with fetch() using Javascript

Presently, I have a setup with a NodeJS + ExpressJS client-side server that communicates with the back-end server via API calls. However, every time I make a call, I need to manually navigate to the URL of the API back-end server and click on Advanced -> ...

What is the significance of providing a sole argument to the Object () function?

Answering a related question about object constructors, what is the intention behind passing an argument to the constructor of objects and using it in this specific manner? function makeFoo(a, b) { var foo = Object.create(Foo.prototype); var res ...

Pressing the submit button will trigger the execution of a .php script, which will then generate a popup on the screen and refresh a specific part of

I have a select form and submit button on my page, which are dynamically generated based on entries in the database. Here is the HTML output: <div id="structures"> <h1>Build</h1> <form name="buildForm" id="buildForm" method="POST" ons ...

retrieving a key from a JSON object

Currently, I am developing a Blazor application where I have encountered an issue with extracting a value from a Json string. The Json data that I am working with looks like this: {"a1":"a1234","e1":"e1234} I specificall ...

Discovering the highest value in the final row of a two-dimensional array

I'm currently working on extracting the maximum value from the last column of a specific array and printing it out. Despite attempting to utilize the Double.max() method, I have encountered issues with it not functioning correctly for this particular ...

Ensure that PHP form validations are checked when submitting the form using jQuery

I have created a form in HTML with basic verification. Here is the code: <form class="" action="submit/save" method="POST" enctype="multipart/form-data" id="submit_form"> <input class="form- ...

Is the unavailability of nodejs's require function in this closure when using the debugger console due to a potential v8 optimization?

I am facing an issue with using the require function in node-inspector. I copied some code from node-inspector and tried to use require in the debugger console to access a module for debugging purposes, but it is showing as not defined. Can someone help me ...

Generating a two-dimensional array and setting its values in JavaScript

I need assistance with creating and initializing a two-dimensional array in JavaScript within an AngularJS application. My current approach is as follows: $scope.invalidVote = []; for (var i = 0; i < $scope.arry1.length; i += 1) { $scope.answersCou ...

An unusual problem stemming from jQuery/AJAX arises when variables within a function fail to update while a click

I've been struggling with a small issue for the past three days that I just can't seem to resolve. It doesn't seem to be a coding error, but rather a misunderstanding of variables and why the onClick event isn't functioning properly. H ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

What is the correct method for exporting an ES6 module function as a library to be utilized in a Node.js application?

Imagine having a node.js application that does not pass through webpack bundling: Node App const Html = require('./build/ssr-bundle.js'); let result = Html.ssrbundle.render(); console.log(result); Here is my ES6/JSX file, which undergoes web ...

Dynamically loading Ember templates with asynchronous requests

I need a way to dynamically load HTML content from another file using the code below: App.MainView = Ember.View.extend({ template:function(){ $.ajax({ url: 'views/main.html', dataType: 'text', async: false, ...

ReactJS: Difficulty with SVG foreignObject not capturing onClick event

Utilizing React Digraph for developing an interface where users can construct and modify state machines. The current functionality is decent, especially in terms of node manipulation via keyboard shortcuts. However, I aim to enhance the user experience by ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

Ensure that the three.js script remains in a fixed position on a page that can be

Is there a way to make a 3D model created with three.js have a fixed position on a scrollable page, like a background while the rest of the content scrolls normally? Are there any CSS techniques or additional script elements that can be used to achieve thi ...

Is it truly necessary to remove packages from devDependencies to improve performance?

It is a common understanding that packages listed under devDependencies are typically not included in the final build. So why do we remove them for the sake of performance optimization? For instance, there are discussions about replacing Moment.js with a ...

Emails not being sent by Nodemailer

I recently configured my glitch project with a contact form and I'm attempting to set it up so that it sends me an email when someone fills out the form. The issue I'm experiencing is that while the server console logs indicate that the message h ...