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

Guide on how to modify a static css file using Node.js

Issue Whenever a user updates the theme on the front-end, my Node.js API needs to update the static CSS file located in a public folder set up by Express. This way, when pages are served again with <link href="public/theme.[userId].[hash].css", the use ...

Transmitting data via POST method within datatables ajax call

I am facing an issue while attempting to execute a simple ajax call in datatables that relies on a post array of IDs from a form on a previous page. The error I encounter is: Invalid JSON Response This indicates that the JSON array being returned may be ...

Error: Authorization requires both data and salt arguments

As a novice in NodeJS, I attempted to create an authentication form using NodeJS + express. The issue I am facing is regarding password validation - specifically, when "confirmpassword" does not match "password", it should return nothing. Despite my effo ...

Is there a way to prevent the text in my text boxes from staying there when I refresh the page?

Currently working on an HTML5 project with Javascript, here is a snippet of my code: Your inquiry <textarea type="text" name="phrase" id="phrase" cols="50" rows="5" placeholder="Write your text here. . ."></textarea> I am looking for a way ...

What methods can be used to evaluate the efficiency of AngularJS in terms of DOM rendering?

Currently working on improving an AngularJS project and looking for ways to identify areas of improvement, such as memory leaks, browser performance, data rendering issues, and screen freezes. I attempted using Jmeter but it only shows page navigation spee ...

Having trouble with the mouse trail code on codepen.io

I am currently attempting to integrate this specific CodePen sample into a Hugo template called Somrat Theme. I'm facing challenges in deciding where to place the HTML file; only the 'no cursor' section should go into style.css, and I need ...

The Python/JSON error message is stating that only integers or slices can be used as indices for lists, not

Having battled for hours, I could really use your assistance. Seeking a single result from a JSON response. Here is how the JSON file appears: https://i.stack.imgur.com/FwRzG.png The desired outcome should be "Desnoss," and it should only appear once. dat ...

What is the best way to increase the value of a variable using jQuery?

As I work on adding dates to a slider, I find myself needing to increment the values with each click. Initially, I start with the year - 2. $('#adddates').click(function() { var year = 2; $("#slider").dateRangeSlider({ bounds: { ...

Omit any items from an array that do not have any child elements

Upon receiving data from the server in the format of a flat tree, I proceed to transfer this data to the JsTree library for tree building. Before sending the data to JsTree, I filter out any empty elements of type "folder" that do not have children. Below ...

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

Guide on attaching an onclick function to a search bar

I found a search bar code on this website and I want to enhance it by adding a function that redirects users to a URL when they click on the search icon. Here is the existing code: <svg xmlns="http://www.w3.org/2000/svg" style="display:none"> ...

Developing an interface that utilizes the values of an enum as keys

Imagine having an enum called status export enum status { PENDING = 'pending', SUCCESS = 'success', FAIL = 'fail' } This enum is used in multiple places and should not be easily replaced. However, other developers migh ...

Ensure that the page has completely loaded using WebdriverJS

Is there a reliable method to ensure that a page has fully loaded using selenium-webdriver in JavaScript? I came across this similar query, but I require an implementation specifically in JavaScript. var webdriver = require('selenium-webdriver') ...

Verify if a certain value exists in an array while using ng-if inside ng-repeat

Currently, I have a loop using ng-repeat that goes through a list of wines obtained from an API. Alongside this, there is an array variable containing all the IDs of wines that have been marked as favorites and retrieved from the database. My goal is to sh ...

Utilizing Ajax in conjunction with Ruby on Rails

I have a question that may be quite basic (I am new to Rails 3). I am looking to implement Ajax functionality where once a user clicks on a link, it triggers a $.post call and initiates some server-side changes. Within the _share partial file, I currently ...

How can I show a view page in a specific div element using CodeIgniter?

Here is how I'm implementing the dashboard view in my controller. My goal is to have a specific page, like the index page, displayed within a div element rather than opening in a new tab. public function index() { $this->load->view('in ...

Why does the error message "$(…).functionName() is not a function" occur and what steps can be taken to prevent it from

I have encountered a console error message: $(...).functionName() is not a function Here is my function call: $("button").functionName(); This is the actual function: $.fn.functionName = function() { //Do Something }(jQuery); What ca ...

Is it possible to modify this code to accept multiple IDs at once?

I'm attempting to create a form in JavaScript where, upon entering the necessary details and clicking submit, the user's email client opens with the information pre-filled for easy sending. However, I am facing challenges as my code involves mult ...

The hierarchy of precedence when using the TypeScript Type Assertion operator

Is it necessary to wrap the js-ternary operator with 'as' Type Assertion? ios ? TouchableOpacity : View as React.ElementType Will it automatically use the result of '?:' since it comes first? Or would a better implementation be: (ios ...

Verify if a <select> element exists inside the main div

Is there a way for me to check if a <select> element is present within the parent div and display certain content based on its existence? Appreciate any assistance! ...