Tips on converting an array list to JSON format

I am attempting to extract the JSON object from an array list

arrayList [
0: {name: "01", value: "3424234234"} 
1: {name: "17", value: "26021734"}
2: {name: "10", value: "435345"} 
3: {name: "21", value: "3453"}]

The array above has been converted to JSON as shown below

var aiCode = {};
aiCode = Object.assign({}, arrayList );

The current result is displayed below

aiCode 
{
0: {name: "01", value: "3424234234"} 
1: {name: "17", value: "26021734"} 
2: {name: "10", value: "435345"} 
3: {name: "21", value: "3453"} 
}

However, I require the following format for the result

aiCode: 
{
01: "3424234234", 
17: "26021734", 
10: "435345", 
21: "3453"
}

What steps should I take to achieve the desired JSON stringification mentioned above

Answer №1

To achieve this, you can utilize the Array#reduce method.

var result = arrayList
  // looping through the array elements
  .reduce((obj, element) => {
    // defining object property 
    obj[element.name] = element.value;
    // returning the updated object
    return obj;
    // starting with an empty 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

The NODE.JS application becomes unresponsive when attempting to retrieve 2.5 million records from an API

I'm facing an issue where my app is retrieving millions of rows from a database and API, causing it to get stuck after calling the getData() function. let closedOrdersStartDate; preparedOrdersPromise = tickApiConnector.obtainT ...

What modifications need to be made to the JSON function in order to ensure its functionality

When trying to access a JSON URL, I encountered the following issue: jsonobject = JSONfunctions .getJSONfromURL("http://192.168.0.219:90/flexlocation2"); Utils.log("json function: " + jsonobject); However, the JSON function returned null ...

Build a custom loader in Next JS that leverages Webpack to dynamically map URL paths to specific components

I am looking to implement a custom loader in Next.js that leverages Webpack through the next.config.js configuration file. This loader should route Blog.js for the /blog route and Tutorial.js for the /tutorial route. The MDX data is stored in the pages/ d ...

JavaScript button click changes the selected row's color in a DataTable

I am looking to dynamically change the color of a row in my Datatable when a specific button is clicked. Here is the HTML code snippet for the rows: <tr role="row" class="odd"></tr> <tr role="row" class="even selected"></tr> & ...

Limiting the style of an input element

How can I mask the input field within an <input type="text" /> tag to restrict the user to a specific format of [].[], with any number of characters allowed between the brackets? For example: "[Analysis].[Analysis]" or another instance: "[Analysi ...

Using Mongoose to Perform Lookup with an Array as a Foreign Key

In my database, I have a collection called questions which contains fields like _id, name, and more. Additionally, there is another collection named tests with fields such as _id, name, and an array of questions. My goal is to retrieve all the questions a ...

What steps can be taken to resolve the error message "JSON parse error - Extra data: line 8 column 3 (char 153)" in the Django Rest Framework?

When trying to create a new post with the following code: { "Number": 1, "name": "1005001697316642", "image": "https://", "description": "fffffffff", "price": & ...

Enhance JQGRID by increasing the row width, changing the color of the column header text, and adjusting the size

I have created a script that pulls data from a database and presents it in a JQGRID table. My goal is to adjust the width of each column in the jqgrid. How can I achieve this? Is there a specific function I should use for this? Additionally, I'd lik ...

What is the origin of the libraries found in npm-shrinkwrap that do not match the packages listed in package.json?

I'm puzzled by the presence of `express` in my `npm-shrinkwrap` file as a main dependency. Despite this, `express` is not listed as a dependency in my `package.json` file. I can't find any usage of it in my project. It's not included a ...

Guide on triggering a bootstrap popup modal using a TypeScript file

I am currently working on an Angular project where I need to launch a popup modal when my function is called. I came across an example on w3schools, but it only contains the HTML logic to open the popup. What I want to achieve is to open the popup from th ...

What is the best way to execute multiple controller functions for a single route?

I have a specific route set up for users to submit loan applications. What I want to achieve is to call different controller functions based on the amount of the loan that the user is applying for. app.use('/submitLoanRequest50kMore', mw1, mw2, ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

Angularfire2: Access Denied Error When User Logs Out

When utilizing the following method: login() { this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then(() => { this.router.navigate(['']); }); } An error occurs during logout: zone.js:915 Unca ...

Can one verify if an Angular application currently has active app modules running?

I am developing a unique plugin for Angular that is designed to automatically initialize an Angular app module if none are found. However, if there is already a running or declared ng-app, my plugin will utilize that existing module instead. Here is an i ...

Troubleshooting issue with changing label text using innerHTML in JavaScript

In need of some advice regarding a javascript function I've been working on: function validateFile() { var file = document.getElementById('fuCSV'); if (file.value == "") { document.getElementById(&apo ...

Dynamic text displayed on an image with hover effect using JavaScript

Currently, I am in the process of developing a website for a coding course that is part of my university curriculum. The project specifications require the use of JavaScript, so I have incorporated it to display text over images when they are hovered over ...

Toggle the class and execute the order within a jQuery script

When the mouse moves in, the jQuery trigger enters the status. $(".test").bind("mouseenter mouseout", function(event) { $(this).toggleClass("entered"); alert("mouse position (" + event.pageX + "," + event.pageY + ")"); }); .entered { ...

Retrieve the specific JSON object chosen from a MongoDB find query

Below is a snippet of JSON data for reference: [ { "_id": "123456789", "YEAR": "2019", "VERSION": "2019.Version", "QUESTION_GROUPS": [ { "QUESTIONS": [ { "QUESTION_NAME": "STATE_CODE", "QUE ...

The declaration of the 'type' in NestJS goes unused, according to ts(6133)

I have a code snippet where the keyword 'type' is highlighted in red and triggering an error message: 'type' is declared but its value is never read.ts(6133) The snippet of my code looks like this: @ManyToMany(type => RoleEntity, ro ...

Ensure that Template.fromStack() includes resources with the specified logical identifiers

Currently, I am overhauling a CDK stack in TypeScript that has reached the resource limit. Given that it includes stateful resources, I need to ensure that the revamped stack points to the same resources and not new ones that could lead to unfavorable resu ...