Implementing the array name property in a JSON object using ES5

I am currently working with a JSON object that has the following structure:

{"Firstname":"john","Lastname":"doe"}

My goal is to transform it into an array with a specific name 'abc':

users: [{"Firstname":"john","Lastname":"doe"}]

This is how I am constructing my object using input values:

var obj = {};
obj.Firstname = document.getElementById("firstName").value;
obj.Lastname = document.getElementById("surname").value;
 console.log(obj);
var jsonStringObj = JSON.stringify(obj);
 console.log(jsonStringObj );

and when I run this code, it outputs:

{"Firstname":"john","Lastname":"doe"}

Thank you for your help!

Answer №1

To solve this, simply create a new array and add the entire object to it.

let person = {"firstname": "Alice", "lastname": "Smith"};
let newArray = [];
newArray.push(person);

console.log([{"firstname": "Alice", "lastname": "Smith"}])

Answer №2

To construct a new entity, with the 'user' key mapped to an array containing your specific item, follow these steps:

let jsonObject = {user: [JSON.stringify(object)]};

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

Node.js and Angular.js communication: from requests to responses

Efforts are being made to solicit data from a node.js server through angular.js. However, an unexpected challenge persists: post-data response, a stark white browser screen shows up with the JSON object in plain sight. The goal is for angular.js to acknowl ...

Transferring information from JSON to HTML

Recently, I came across this handy design tool within our service that helps generate Gauge charts by simply adding a specific div class to the desired pages. <div class="gauge" id="g0" data-settings=' { "value": ...

obtain the image number by extracting a portion of the text

How can I extract the image number from a string using the sub-string function? I have applied the sub-string function to the property below. It returns 3 at the end in Chrome, but it does not work properly in Mozilla. Issue : After "-->", when I chec ...

Managing two simultaneous web service calls in Angular 2

Dealing with two parallel web service calls can be tricky. Sometimes the first call goes through first, and other times it's the second one. The problem arises when the function in my second service requires data from the first service call. I attemp ...

How to prevent text from overflowing outside the Material UI Container/Box?

One issue I'm facing is with an Alert that displays long strings on my website. Here's the code snippet in question: <Container maxWidth="md"> <Box sx={{ mt: 3, border:1}}> <Box> {hasSubmitted ? ...

Press the toggle button to switch the image display

Currently learning HTML and attempting to design a dashboard. I want to display the status (ON, OFF, OPEN, or CLOSED) of a room or door using an icon. I have images for open/close doors and lightbulbs. Need assistance in adding an element to all the exist ...

Working with time durations in JavaScript

Is there a way to calculate the duration between a start time and an end time including both hours and minutes? Currently, I have code that only provides me with the hours. Is there any modification I can make to include minutes as well? If so, what chan ...

Providing Express with static files

I have created a Node.js application using express. When I make a request to /, I want to serve the file located at /public/app/index.html. This part is working fine. However, within the index.html file, there are references to two CSS and two JS files wit ...

Using Ant Design with Formik to dynamically set field values in a form

When I click the "Change" button in an Antd table with data, the entire line of data is passed to a function as an object. However, I am having trouble inserting the data into the fields. What should I do? How can I set data to Antd input using an externa ...

Calculating hash values for JSON columns in Spark

In a Cassandra table, the last column named "fullJson" contains JSON log files. I am trying to hash the userID values in these JSON lines using MD5. Despite my approach, I always encounter issues at some point. The Cassandra table has been loaded successfu ...

"Utilizing JSON information to create visually appealing graphs and charts

Struggling with syntax and in need of assistance. I have a basic data set that I want to display as a timeline with two filled lines (Time Series with Rangeslider). This is the format of my data set: [{"pm10": 12.1, "pm25": 7.0, "time": "13.08.2018 12:25 ...

Header Overflow Error Encountered in Node.js GET Request

While attempting to programmatically submit a form through Google forms using a GET request, I encountered the error message Parse Error: Header overflow. The debug code output is as follows: REQUEST { uri: 'https://docs.google.com/forms/d/e/9dSLQ ...

Replace a string in an array using JavaScript

I may be overlooking something very obvious, but here is my dilemma. I am trying to convert [ 'hr' ] into [ '* * *' ]. This is what I tried: var hr = jsonml[i] console.log(hr) // outputs: [ 'hr' ] hr.replace(/hr/g, '* * ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

Creating a tree structure from a one-dimensional array with the help of dual data tables in JavaScript

I'm struggling to create a tree structure from a flat array using two Mock data tables in JSON. The table should match the unique IDs to determine the hierarchy between them. JSON with Groups DB array example: { "group": [ { "groupName" ...

Ways to extract the necessary key value from a JSON Response in JMeter

Can someone assist me in validating the 'IsActive' value for 'SysCreatedUserId' or a specific 'Id' in a JSON format API response? Below is the JSON file I am working with, and so far, my attempts with JSON Assertion have been ...

Capturing an error within an asynchronous callback function

I am utilizing a callback function to asynchronously set some IPs in a Redis database. My goal is to catch any errors that occur and pass them to my error handling middleware in Express. To purposely create an error, I have generated one within the selec ...

Invalid component exception: The element type is not valid in React Native

In my React Native App.js file, I have included the following code snippet import { StatusBar } from 'expo-status-bar'; import React, { useRef } from 'react'; import { StyleSheet, Text, View, Canvas } from 'react-native'; impo ...

Angular - remove elements from an array within a directive when encountering a source error

If an image does not exist, I need to remove the item and push the next one inside ng-repeat. Currently, I am using a custom directive called "noImage". myApp.directive("noImage", function() { return { link: function(scope, element, attrs) { ...

Is the branch of ExtJS 4.1 TreeStore lazy loading extending?

I am working on implementing lazy loading of tree branches in an MVC application using extjs4.1. The branches are located on different URLs and I have faced several challenges along the way. Unfortunately, at this point, the branching functionality is not ...