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

Storing JSON data in an array using JavaScript is a powerful method to

Here is an example of JSON data: [{ "address": "A-D-1", "batch": [{ "batch_number": "B-123", "cost": [{ "cost": "C1" }] }] }, { "address": "A-85-1", "batch": [{ "batch_number": "B-6562", ...

Python JSON load results in a Connection Forcibly Closed error

Overview: Utilizing Python 2.7 along with the urllib2 and json libraries, I am making an API call. However, upon running the script, I encounter the following error if the results count exceeds 20: Error: [Errno 10054] An existing connection was forcibl ...

Not revealing the complete values of the specified column through the utilization of implode

<?php $data='{ "id": "621805046", "likes": { "data": [ { "category": "Movie", "name": "Pyaar Ka PUNCHnama", "created_time": "2013-08-13T10:11:23+0000", "id": "151480271575584" }, { ...

Retrieve an array from the updated scope

I need help with my code. How can I retrieve the names from an array and display them in my input box? Also, how do I get all the changed names back into the array? Thanks in advance! - Marco app.js var g[]; var names = ['John', 'Steve&apo ...

Is there a way to retrieve the io object within the io.sockets.on callback function?

My preference is to not alter my sockets method. I was hoping to be able to utilize the io object within the connected function. Could this be a possibility? function sockets (server) { const io = require('socket.io')(server); io.sockets.on ...

Sequential execution not functioning properly in NodeJS Async series

Here is the code snippet I am working with: var async = require('async'); var rest = require('restler'); async.series([ function(callback){ rest.get('https://api.twitter.com/1.1/statuses/mentions_timeli ...

Is my input file in Javascript valid and does it exist? Here's how to check

In my Javascript code, I am retrieving strings from a text file. When the user inputs an incorrect or invalid file name, I want to display a message. For example: console.log("Your input is invalid"); Here is the code snippet that reads the text file and ...

What are the steps to execute a filter operation on a table by utilizing two select box values with jQuery?

I have a challenge with two dropdown menus. One contains names and the other subjects, along with a table displaying information in three columns: name, subject, and marks. I would like to implement a filter based on the selections in these two dropdowns. ...

Zoom out the slider when scrolling

Take a look at this link and as you scroll down the page, notice how the image transitions to iPhone. Can anyone provide insight on how this effect is achieved? ...

Is Ruby on Rails featured in Designmodo's Startup Framework Kit?

I'm curious if the Startup Framework Kit from Designmodo can be seamlessly incorporated into my Ruby on Rails project. While I've had success integrating their Flat-UI-Pro using a gem, I haven't come across one for the Startup Framework yet. ...

Transforming text into numbers from JSON response with *ngFor in Angular 6

I'm currently attempting to convert certain strings from a JSON response into numbers. For instance, I need to change the zipcode value from "92998-3874" to 92998-3874. While doing this, I came across a helpful resource on Stack Overflow. However, I s ...

Discover the steps to capture the ajax initiation and completion events

In my application, I have numerous ajax requests. To display a loading symbol while these requests are in progress, I am utilizing jquery ajaxStart and ajaxStop methods. However, for some reason, they seem to not be functioning as expected. Despite searc ...

Techniques for retaining the revised stock total following subtraction? [PHP-JSON]

How can I update the remaining stock quantity after a purchase in PHP using JSON? I am trying to deduct the quantity bought by a customer from the current stock, save it in order.json along with the total payment, and then update food.json. However, I&apo ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...

Modify an element on one webpage using a function called from another webpage

I am currently working on a website design that involves displaying images on various frames. While I have managed to change content across different frames, I am now exploring the possibility of changing content across different web pages. Here is the se ...

Javascript's second element does not trigger a click event with similar behavior

I'm currently facing an issue with displaying and hiding notification elements based on user interaction. My goal is to have multiple popup elements appear when the page loads. Then, when a user clicks the ".alert-close" element within one of the popu ...

transferring data through AJAX using the POST method

When attempting to utilize the POST method to send a variable containing a name to a server asynchronously, I encountered an error message: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Unfortunately, this error was n ...

Can we programmatically extract content from an Instagram page with the URL ending in ?__a=1?

https://www.instagram.com/example/?__a=1 When you attach ?__a=1 at the end of an Instagram account link, a json page is generated that includes various user information such as: {"logging_page_id":"profilePage_11288110","show_suggested_profiles":false,"g ...

There was a failure to establish a Redis connection to the server with the address 127.0.0.1 on port 6379

Currently, I am working with node.js using expressjs. My goal is to store an account in the session. To test this out, I decided to experiment with sessions by following the code provided on expressjs var RedisStore = require('connect-redis')(ex ...

Ways to retrieve JSON objects from the Controller using ajax

Currently, I am developing a mail validation controller using jQuery AJAX and PHP. Once the message is validated in the PHP controller, I attempt to retrieve it using AJAX and display it on the screen using jQuery. Here is an excerpt of my AJAX code: .. ...