Converting objects into JSON format

I'm trying to transform an object that looks like this:

{  
  user[id]: 1,  
  user[name]: 'Lorem',  
  money: '15.00'  
}

Into the following structure:

{  
  user: {  
    id: 1,  
    name: 'Lorem',  
  },  
  money: '15.00'  
}

Can anyone help me accomplish this transformation?

Answer №1

Here is an example:

var x = {  
  "user[id]": 1,  
  "user[name]": 'Lorem',  
  "money": '15.00'  
}
var y = {};
for (var i in x){
    var  z = /(.+)\[(.+)\]/g.exec(i);
    if (z){
        if (!y.hasOwnProperty(z[1])){
            y[z[1]] = {};
        }
        y[z[1]][z[2]] = x[i];   
    }
    else{
        y[i] = x[i];
    }
}

Check out this link for more details

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

When incorporating multiple BoxGeometries, THREE.js ensures that each box maintains a consistent color throughout. The uniformity remains unchanged

Looking to create a simple program using Three.js to display bars at specific locations with varying heights and colors. As a beginner in Three.js, I am currently exploring the framework. When running my script to set up the bar positions, colors, lights, ...

Transmit both image and JSON data in a single response using Node.js and Express

I'm in the process of building a web API using Node.js and Express and my goal is to send back both an image and JSON data in a single response. I came across a solution that involves specifying headers at , but I'm looking for a way to achieve t ...

What improvements can I make to enhance my method?

I have a block of code that I'm looking to clean up and streamline for better efficiency. My main goal is to remove the multiple return statements within the method. Any suggestions on how I might refactor this code? Are there any design patterns th ...

Ways to pass data to the main table's field using JSON

Client entity @Entity @Table(name="Client") public class Client { @Id @GeneratedValue private Long clientId; @Column(name="first_name") private String firstName; @Column(name="last_name") private String lastName; ...

Unable to edit the current value of an input component in ReactJS

I need to implement a search feature for a list of items using ReactJS. You can view the project on JSBIN. The issue I am facing is that when I input 'mi' in the search box to filter by ID, the filtration works correctly but the input value does ...

Error: When attempting to access the 'name' property of an undefined object, a TypeError is thrown. However, accessing another property on the same object does

Retrieving information from API. The fetched data looks like [{"_id":"someId","data":{"name":"someName", ...}}, ...] My state and fetching process are as follows: class Table extends React.Component { constructor() { super(); this.state = { ...

Flask API does not recognize elif and else conditions

Creating a flask API that deals with various nested JSON files presents an interesting challenge. Depending on the data within these files, different actions need to be taken. The sorting logic is based on conditional statements as shown below: if (jsonFi ...

Divinely favored - pay attention for each and every sound

Currently, I am utilizing node with the blessed tty library downloaded from NPM. Within this library, there is a method called "key" that I am using in the following way: blessed.key(['q', 'z'], function(ch, key) { //do something ...

When the CSS animation has finished in JavaScript

I am currently developing a game using HTML/JavaScript, and I have implemented a "special ability" that can only be activated once every x seconds. To indicate when this ability is available for use, I have created a graphical user interface element. Since ...

Transfer a file from the file:///var/mobile/Applications/ directory to an accessible location for reading in Cordova/PhoneGap

I have a unique 'whitelabel' app that customizes itself for each client by downloading image files from a configuration server. However, I am facing an issue where the images are not displayed and instead showing a "Not allowed to load local reso ...

The function setState() is not performing as expected within the useEffect() hook

After retrieving data from my Mongo database, it's returned as an object within the useEffect hook function, specifically in the response. I then initialize a state called myorders with the intention of setting its value to the data fetched from the A ...

How can I transmit a pong frame using WebSocket in javascript/NodeJS?

I am struggling to locate a proper example demonstrating how to send a PONG response using javascript/NodeJS within the context of a WebSocket connection (back to a server that requests it after sending a PING request). Can anyone provide guidance on thi ...

Performance problem with 'Point-along-path' d3 visualization

I recently explored a d3 visualization where a point moves along a path, following the code example provided at https://bl.ocks.org/mbostock/1705868. During this movement, I observed that the CPU usage ranges from 7 to 11%. In my current project, there ar ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

One approach to returning multiple objects based on a column with multiple values in Dynamic Linq

Situation: I am facing a task where I need to export an excel file containing a list of Parts. Users have the ability to select specific columns and only retrieve data from those selected columns in the exported file. To handle this dynamic report, I have ...

React Alert Remove Alert: Each item in a list must be assigned a distinct "identifier" prop

How can I resolve the React warning about needing a unique "key" prop for each child in a list? I'm trying to eliminate the warning that says: "Each child in a list should have a unique key prop." The code snippet causing this warning is shown below ...

Transform Java String to HashMap Instance

After successfully creating an application to convert a HashMap object to String, I encountered an issue while trying to convert the HashMap string back to a HashMap object. When I attempted this conversion using the provided code snippet, it resulted in a ...

The JSON StackOverflowError occurs when there is a parent-child relationship between two objects

While attempting to establish a parent-child relationship between various objects, I encountered a challenge. In my scenario, I am aiming to organize objects within other objects (for example, a container holding multiple items or other containers with it ...

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

What is the best way to change the location of a jQuery Mobile global popup?

I have a jQuery Mobile global popup that is initially empty and generated dynamically. I am utilizing the beforeposition event to detect when the popup opens. At this point, I load a configuration file or content file, create the content, and then add it t ...