Generate a JSON line for each value in the ARRAY

Hello everyone, I'm currently working on implementing handlebars templating and to do so I need to generate a JSON from array values

{"path":"Avions", "fileName":"AvionsEdit.vue"},{"path":"Avions", 
"fileName":"AvionsShow.vue"}etc...

While I can create a JSON like the one shown in the code snippet above, I would prefer the format below:

{"path":["Avions","Avions"],"fileName": 
["AvionsEdit.vue","AvionsShow.vue"]}

var foo = {"path" : [], "fileName": []};
for(i = 0; i < list.length; i++) {
   foo.path.push(list[i]);
   foo.fileName.push(list[i]+extList[i]+".vue");
}
console.log(JSON.stringify(foo));

Here is the list I'm working with:

['Avions',
'Avions']

And here is the extList corresponding to each item in the list:

['Edit',
'Show']

Answer №1

Feeling a bit old-fashioned with my reliance on nested for loops, but I couldn't come up with a better solution (although it's quite reliant on data consistency, it's still pretty simple and easy to read):

var srcData = {
  "path": [
    "somepath",
    "anotherpath",
    "yetanotherpath"
  ],
  "filename": [
    "somefilename",
    "anotherfile",
    "yetanotherfile"
  ]
};

const transform = src => {
   let res = [];
   let attributes = Object.keys(src);
   for(let i = 0; i < Object.values(src)[0].length; i++){
      let entry = {};
      for(let j = 0; j < attributes.length; j++){
          entry[attributes[j]] = Object.values(src)[j][i];
      }
      res.push(entry);
   }
   return res;
};

console.log(transform(srcData));

Answer №2

I missed out on viewing your latest comments as I was anticipating notifications that never arrived. I've developed a function that can produce the desired output. The various arguments required are:

  • Path : List of paths or prefixes
  • File : File name
  • suffix : Suffix/extension of the file

var path = [ // list of paths or prefixes
      "path",
      "otherPath",
      "finalPath"
    ];
    var files = [ // file names

      "Edit",
      "Get",
      "Foo"

    ];
console.log(transform(path, files, ".vue")); 


 function transform(path, files, suffix) { // receives paths, file names, and file suffix
      if (path.length == files.length) { // checks if the lengths are equal
        let results = { "path": [], "filename": [] }; // initializes object for return
        for (let i = 0; i < path.length; i++) {
          results.path.push(path[i]); // adds path to path array 
          results.filename.push(path[i] + files[i] + suffix) // generates file name by concatenating Path + File + suffix

        }
        return results;
      }
    }

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

Disposing of memory in THREE JS when switching between routes in VUE

Currently, I am delving into the world of VUE JS and working on a basic SPA that navigates through different pages. In my spare time, I have developed several THREE JS demos which unfortunately tend to slow down and eventually halt when switching between ...

Why is this tetris piece not appearing fully on the grid when using arrays?

Below is the code snippet, and you can find a link to the jsfiddle below. I'm facing an issue where the first row of the block is not being drawn, and dealing with these 2-dimensional loops is quite challenging for me. I am unable to figure out why t ...

Vue.js: Issue with applying class binding while iterating over an object

I've been working with an object data that looks like this: object = { "2020092020-08-01":{ "value":"123", "id_number":"202009" }, "2020092020-09-01":{ "value& ...

Deciphering the intricacies of VUEX-STORE modules

Consider this scenario: I have two separate lists - one for income and one for outcome. Each list has its own storage, and I am adding these storages as modules in index.js. While I could create a single repository for both income and outcome, displaying ...

To ensure at least one checkbox is selected, retrieve the values from the checkboxes and proceed to store them in a state variable for validation

Our form allows users to submit multiple answers in a checkbox format. I'm utilizing the useState hook to manage the answers and validate the array size to determine if the button should be enabled or disabled. Currently, the issue is that even after ...

JavaScript code for Tree not functioning correctly on Internet Explorer

Seeking assistance to fix a bug in my JavaScript program. The code works perfectly on Google Chrome and Firefox, however it encounters an error in Internet Explorer 8 as indicated below. Any suggestions on how to resolve this issue would be greatly appreci ...

Short-circuiting async flows on non-error events in Node.js

Node implements the CPS convention for callbacks. Typically, when a function encounters an error, it is common practice to either handle the error or callback the error to the parent function by utilizing something like return cb(err). One challenge I fac ...

When modifying the state of an array within a component, certain values may be overwritten and lost in the process

Currently, I'm faced with the challenge of ensuring that a component displays a loading screen until all images have completed loading. This is necessary because there are approximately 25 images that must finish loading before the page can be display ...

Address Book on Rails

Hello, I'm relatively new to this and would be grateful for any assistance. My goal is to utilize the data saved by a user in their address book, and then offer them the option to use that address for delivery. Below is my Address controller: class A ...

Adding a custom property to a React component

Currently, I am facing an issue while attempting to modify an MUI component. Everything works smoothly until I execute the build command, at which point it fails. I have experimented with a few variations of this, but essentially I am looking to introduce ...

Find the name of the class using JavaScript

Is there a more elegant way to retrieve the class name of a class in JavaScript? I have implemented a method and would like to log any errors with a message indicating the class in which the error occurred. My current solution feels a bit "dirty": I am s ...

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

How to send JSON data without specifying keys in Java

The client has provided me with a URL and requested an HTTP POST to be made to that URL using some JSON data. However, the issue arises as the client has not shared the key necessary for posting data in the format "key=json string." Despite my request for ...

Implementing basic authentication in Socket.IO on a Node.js server

Currently, I am attempting to develop a basic websocket client for establishing a connection with a device. However, the device requires both a username and password for authentication purposes, posing a challenge for me as I struggle to figure out how to ...

Presenting JSON output using AngularJS

I'm struggling to showcase JSON response data using AngularJS Despite able to see the results in DevTools, I am facing issues while displaying them on the screen. Here is the controller code: MovieApp.controller('movieAdminCtrl', ['$ ...

Using React for form validation

I'm facing a challenge while trying to develop a user registration form, especially when it comes to displaying form validation errors. Issues: 1) The input fails to post (via axios) to the database upon submission for inputs without errors. 2) The e ...

Node.js version 12.7 does not have the ability to support dynamic keys within objects

According to what I've read about ecma6, it should allow for dynamic key objects. I recently upgraded my node to version 0.12.7, but I'm still encountering an error. node /var/www/games/node_modules/app.js /var/www/games/node_modules/app.js ...

The Material UI Popover is appearing outside the designated boundaries

In my app, I am using the code below to implement a react-dates picker controller inside a popover element. The functionality works well in most scenarios, but there is an issue when the button triggering the popover is located at the bottom of the screen, ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...

The PHP sorted array loses its order when encoded into JSON and then sorted in JavaScript

In my PHP code, I have two arrays that I need to work with. The first array is sorted using the arsort() function like this: arsort($array1); After sorting, I output the contents of both arrays like so: foreach ($array1 as $key => $val) { $output ...