Ways to convert JavaScript object to hashmap

I am attempting to generate a map of type <String, Array()> from a JSON object. Suppose I have the following JSON structure:

[
    {
        "userId": "123123",
        "password": "fafafa",
        "age": "21"
    },
    {
        "userId": "321321",
        "password": "nana123",
        "age": "34"
    }
]

The desired map should have the format:

key (string), value (array)

{
    "userId": [
        "123123",
        "321321"
    ],
    "password": [
        "fafafa",
        "nana123"
    ],
    "age": [
        "21",
        "34"
    ]
}

Would it be possible to achieve this? :/

Many thanks in advance.

Answer №1

Demo

var data = '[{"productId" : "987", "price": "50", "quantity": "2"}, {"productId" : "654", "price" : "30", "quantity" : "1"}]';

var items = JSON.parse(data);
var result = {};

for(var j=0; j<items.length; j++)
{
    for(var itemKey in items[j])
    {
        if(items[j].hasOwnProperty(itemKey))
        {
            if(typeof result[itemKey] == 'undefined')
            {
                result[itemKey] = [];
            }
            result[itemKey].push(items[j][itemKey]);
        }
    }
}

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

Generated Output:

{"productId":["987","654"],"price":["50","30"],"quantity":["2","1"]}

Answer №2

function mergeObjectsProperties(inputArr) {
  return inputArr.reduce(function(accumulator, currentObj) { // Iterate through each object in the array.
    Object.keys(currentObj).forEach(function(key) { // Iterate through each key in the current object.
      if (!(key in accumulator)) { accumulator[key] = []; } // Create an empty array for the key if it doesn't exist.
      accumulator[key].push(currentObj[key]); // Add the property value to the corresponding key's array in the accumulator.
    });
    return accumulator;
  }, {});
}

var jsonData = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';

mergeObjectsProperties(JSON.parse(jsonData));
// {
//   "userId": ["123123", "321321"],
//   "password": ["fafafa", "nana123"],
//   "age": ["21", "34"]
// }

Answer №3

By using Javascript's JSON.stringify method, you can easily transform a JSON compatible object structure into a JSON string.

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

Tips for restricting users from inputting spaces into a form field using ReactJS

Within my application, I have developed a specialized component named QueryForm that serves the purpose of enabling search capabilities. The code snippet being outputted by this component is as follows: ...

Clicking the mouse within three.js

I'm facing an issue with my webpage that features a three.js (webgl) graphic created using a .dae file imported from Blender. My goal is to draw a square or mark wherever the mouse is clicked, but for some reason, the square appears in a different loc ...

What is the recommended data type to assign to the `CardElement` when using the `@stripe/react-stripe-js` package in TypeScript?

I'm struggling to determine the correct type to use for this import: import { CardElement } from '@stripe/react-stripe-js'; I have successfully used the types Stripe, StripeElements, and CreateTokenCardData for the stripe and elements props ...

Enhance Summernote functionality by creating a custom button that can access and utilize

Using summernote in my Angular project, I am looking to create a custom button that can pass a list as a parameter. I want to have something like 'testBtn': this.customButton(context, listHit) in my custom button function, but I am unsure how to ...

Looking to construct dynamic checkboxes in Angular by parsing a JSON object retrieved through AJAX

I have a JSON document structured like the example below, and I am looking to generate checkboxes dynamically using Angular. let data = { "Name":[ { "tagId":4489,"name":"Name","label":"Employee Name" } ], "Service":[ { "tagId": ...

Using Angular JS version 1.2.26 to implement promises within a forEach iteration

I am working on a JavaScript project where I have implemented an angular.forEach loop to iterate over image configuration objects and create Image() objects using the URLs from the config. My goal is to ensure that none of the resulting images are returne ...

Unable to render Angular charts

Recently, I've been attempting to integrate angular charts using the chart.js bundle sourced from CDN links. The version of Angular being used is 1.5.7 and for chart.js it's 2.1.6. I encountered the following error message: angular.js:13708 T ...

The ideal formats for tables and JavaScript: How to effectively retrieve arrays from a table?

Given the task of defining a function that extracts the mode of weights from an HTML table containing age and weight data for individuals within a specified age range. The function needs to be able to handle tables of any size. I am looking for the most ef ...

Replace the content within the iFrame completely

Is it possible to have a textarea where I can input HTML code and see a live preview of the webpage in an iframe as I type? For example, here is the code I'd like to write in the textarea: <!DOCTYPE html> <html> <head> ...

What steps should I take to generate a stylized date input in javascript?

Looking to dynamically create a date string in JavaScript with the following format: dd-MMM-yyyy Need the dd part to change between 1 and 29 each time I generate the variable within a loop Month (MMM) should be set as Jan ...

Encountering issues with Jackson deserialization when handling nested objects that have interdependent references, leading to UnresolvedForwardReference

I am attempting to deserialize a JSON structure that looks like this: { "node" : { "number" : 5, "x" : 2000.0, "y" : 1500.0 }, "force" : { "number" : 1, "value" : -20.0, "angle" : 90.0, "node" : 5 } } And convert it in ...

How can I verify if a date is after the current date using Node.js?

I am struggling to set up date validation that ensures the date is after the current date. This is what I have attempted so far: Router.post('/home', [ check('due_date') .isDate() .isAfter(new Date.now()) .wi ...

Step-by-step guide on loading images using AsyncTask

Implementing Asynctask to Load Images in Android Using Java @Override protected String doInBackground(String... arg0) { mNewsList = new ArrayList<HashMap<String, String>>(); JSONParser jParser = new JSONParser(); JSONObject json = ...

Determine future dates based on selected date and time

When a user selects a date in the datetimepicker, I want to automatically set three additional dates. The first date will be the selected date + 28 days, the second date will be selected date + 56 days, and the third date will be selected date + 84 days. I ...

Refresh an Angular page automatically

Having a small issue in my angular application. The problem arises on the first page where I display a table listing all employees along with a "Create New Employee" button that opens a form for adding a new employee. However, after submitting the form and ...

Is it possible to execute JavaScript in VSCode without the need for Node.js?

Is there a way to run JavaScript in VSCode using a school-issued laptop that does not allow the download of Node.js? I have searched for alternatives, but most tutorials recommend downloading Node.js. ...

Exploring multilevel JSON data in MariaDB/MySQL to pinpoint a particular value

My current project involves working with a MariaDB table that contains a JSON value stored in the following format: {"nextValue":4,"1":{"text":"Item1","textDisplay":"","value":1,"isActive":0},"2":{"text":"Item2","textDisplay":"","value":2,"isActive":1},"3 ...

What is the best way to switch back and forth between two div elements?

I've been attempting to switch between displaying div .cam1 and div .cam2, however, I can't seem to get it to work. Here's the code snippet in question: HTML: <div class="cam1"></div> <div class="cam2"></div> CS ...

Ways to utilize array reduce for organizing information

Can someone please guide me on how to use the reduce array method to sort entries by date in the following data: const entries = [ {date: 'lu'}, {date: 'lu'}, {date: 'ma'}, {date: 'ma'} ] I would like the ou ...

Unspecified property in Vue.JS data object

Whenever I try to display my modal, an error pops up indicating that the property is not defined, even though I have clearly declared it in the Data(). It seems like there is a crucial aspect missing from my understanding of how everything functions... T ...