JavaScript JSON conversion from a list

If I have two different lists, such as:

list1= ['blue', 'green', 'purple']
list2 = ['circle', 'square', 'triangle']

Is there a way to convert them into a JSON object structure by using another list to determine attribute names?

For instance, if the attributes are defined as ['color', 'shape']

Then the result should look like:

final_result = [
  {color: 'blue', shape: 'circle'}, 
  {color: 'green', shape: 'square'}, 
  {color: 'purple', shape: 'triangle'}]

Answer №1

Here is a function that I have created which accepts two arguments - the first argument being an array of attributes, and the second argument being an array of arrays representing list items. This function will handle cases where the number of attributes is greater than the number of property items provided:

 var create = function(attrList, propertyLists) {
  var result = [];
  var aLen = attrList.length;
  var pLen = propertyLists.length;
  
  if (pLen === 0) {
    return result;
  }

  var itemLength = propertyLists[0].length;
  if (itemLength === 0) {
    return result;
  }

  var i, j, obj, key;
  for (i = 0; i < itemLength; ++i) {
    obj = {};
    for(j = 0; j < aLen; ++j) {
      key = attrList[j];
      if (typeof propertyLists[j] === 'undefined') {
        //
        continue;
      }
      obj[key] = propertyLists[j][i];
    }
    result.push(obj);
  }

  return result;
 };

var a = ['apple', 'orange', 'banana'];
var b= ['red', 'orange', 'yellow'];
var attrs = ['fruit', 'color'];
var jsonObj = create(attrs, [a, b]);
console.log(jsonObj);

Answer №2

If you want to achieve this functionality without using underscore or lodash, you can implement it by creating your own methods. Here's how you can do it:

var attributes = ['animal', 'sound'];
var animals = ['dog', 'cat', 'bird'];
var sounds = ['woof', 'meow', 'chirp'];

//Combine arrays into a list of pairs
//(this process would need to be updated with each new array of attribute values)
//MAINTAIN ORDER FOR CORRECT MATCHING
var zipped = zipArrays(animals, sounds);

//Map the zipped list, returning an object based on the keys. 
//Remember the order of arrays in the zip operation 
//must correspond to the order of attributes in the attributes list
var result = mapZipped(zipped, function(item, index) {
    return createObject(attributes, item);
});

console.log(result);

Answer №3

It is essential to ensure that the lists are of the same size and all elements correspond correctly for this method to function effectively. If there is a discrepancy in sizes, the process will encounter errors. Can you provide insight into your data structure?

\\given
listA= ['apple', 'orange', 'banana']
listB= ['red', 'orange', 'yellow']
categories = ['fruit', 'color']

\\implement the following script
var output = [];
for (var index = 0; index < listA.length; index++){
    output.push({
        categories[0]:listA[index],
        categories[1]:listB[index]
    });
}

console.log(output);
\\output = [
\\    {fruit: 'apple', color: 'red'}, 
\\    {fruit: 'orange', color: 'orange'}, 
\\    {fruit: 'banana', color: 'yellow'}]

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

What is the best practice for adding a DOM element at a precise location within an ng-repeat loop?

I am currently working on developing a podcast player application using AngularJS. At this point, I have successfully created a list of available podcasts that can be played, utilizing ng-repeat. The code for the list is shown below: <ul ng-controller ...

Converting Python dictionaries or JSON data into PHP arrays

There are several threads discussing how to convert python dictionaries to json, but I have not found any information on saving a python dictionary or a json array to a PHP array. I recently inherited a PHP array file that requires some modifications. With ...

Following an AJAX post within the MVC framework, the URL becomes excessively lengthy

http://localhost:53435/Blog/BlogIndex?title=blog+title&seo=seo&content=%3Cp%3Econtent%3C%2Fp%3E%0D%0A the URL listed above Whenever I click the save button, the page refreshes and the URL appears like that. I do not want it, how can I resolve th ...

A helpful guide on displaying validation errors in a form using React JS

After creating a form and connecting it to the server, I encountered an issue with displaying validation errors below respective input fields. The error message response in case of validation error is as follows: "message": "ValidationError: confirmPasswor ...

issue with implementing the chart.js npm package

Just recently, I added chart.js to my project using npm. My goal is to utilize the package for creating graphs. npm install chart.js --save After the installation, I attempted to import the module with: import chart from 'Chartjs'; However, t ...

Searching JSON objects in a dynamic manner

I've been trying to incorporate a dynamic condition in a JSON Object without any luck so far. I haven't come across any resources that cater to my specific requirements. The code snippet below shows how I'm storing the dynamic JsonObject st ...

How can JSON-loaded scripts be executed using jQuery?

I received a file with the following content: {'html' : '<div id="bla">something</div>', 'script' : ' $().ready(function() { /* some code */});' } I want to use jQuery to load this file and execute the ...

"Discover the magic of jQuery: Unveiling the hidden div with one simple CSS visibility change

I want to implement a functionality on my screen where the Previous button is hidden initially and only becomes visible when the user clicks the Next button. I have set the CSS property for the Previous button to hide it by default, but despite using an if ...

Methods for dynamically populating dropdown lists with JavaScript and Bootstrap

I have collected all 387 regions for the current date and now I want to dynamically populate a bootstrap dropdown with these regions using JavaScript. Below is the basic HTML code for a bootstrap dropdown: <div class="dropdown"> <button class ...

Implementing Bootstrap tooltips in content that can be scrolled

I need help with positioning two containers, which you can view in this FIDDLE. Both containers may contain a lot of content, so I have applied overflow: auto to both of them. This is the HTML structure: <div id="maincontainer"> <d ...

Unable to display the content

Why isn't the text expanding when I click "see more"? Thanks XHTML: <div id="wrap"> <h1>Show/Hide Content</h1> <p> This code snippet demonstrates how to create a show/hide container with links, div eleme ...

Transformation of JSON data from Array to Object

I have a JSON data structure that looks like this: { tag: 'new-tag', stream_subjects: [1, 2, 3] } My goal is to transform it into the following format: { tag: 'new-tag', stream_subjects: [ {subject_id: 1}, {subject_id ...

Javascript - Issue: Route.post() is in need of a callback function, however it received an [object Promise] instead

I'm encountering an issue with one of my express routes. The error message I am receiving is as follows: Error: Route.post() requires a callback function but got a [object Promise] This error seems to be related to the last line in controllerFunction ...

The tooltip chart is not displaying all of its data

I create a dynamic tooltip with a custom chart inside of it. tooltip: { borderRadius: 15, borderWidth: 0, shadow: false, enabled: true, backgroundColor: 'none', useHTML: true, shared: true, formatter: function() { ...

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

A guide to mastering Controllers in AngularJS

Trying to set up a basic page with a controller but encountering difficulties. The HTML code is straightforward, with an Angular script included, but the functionality isn't working as expected. The HTML snippet: <!DOCTYPE html> <html ng-ap ...

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 ...

Tips for adjusting the animation position in Off-Canvas Menu Effects

I am currently utilizing the wave menu effect from OffCanvasMenuEffects. You can view this menu in action below: ... // CSS code snippets here <link rel="stylesheet" type="text/css" href="https://tympanus.net/Development/OffCanvasMenuEffects/fonts/f ...

Discrepancy in functionality between .show() and .append() methods within JQuery

I have a container with an ID of "poidiv" that is hidden (display: none) initially. My goal is to dynamically load this container multiple times using a loop, where the maximum value for the loop is not predetermined. I attempted to achieve this using jQue ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...