What is a more efficient method for creating a JSON object?

Here is the code I am using:

this.selectedMonths = JSON.parse(JSON.stringify(this.selectedMonths));

Once this code runs, `this.selectedMonths` will be properly formatted as a JSON object.

I'm wondering if there is a more efficient way to achieve this. The current method of using both JSON.parse() and JSON.stringify() seems redundant.

Side Note: Simply using JSON.stringify() by itself doesn't work because it adds quotation marks around the entire JSON array. That's why I have to use JSON.parse() to remove those quotations.

Answer №1

After understanding your feedback, here is a new approach that involves using the map method to iterate over an array and apply a function named toInteger. The purpose of toInteger is to convert specific keys in the array objects into integers.

let selectedMonths = [{
  id: "1",
  name: "Bob",
  age: "12"
}, {
  id: "2",
  name: "Harry",
  age: "34"
}];

function toInteger(keys) {
  return function(obj) {
    return Object.keys(obj).reduce(function(obj, key) {
      if (keys.includes(key)) obj[key] = Number(obj[key]);
      return obj;
    }, obj);
  }
}

let out = selectedMonths.map(toInteger(['id', 'age']));

console.log(out);

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

What are some methods for simulating user interaction on input and button elements?

Here is a code snippet available in this stackblitz demo. Essentially, there is a basic form with an input field and a button. Clicking the button will copy the current value of the input to a label: https://i.stack.imgur.com/pw3en.png after click: htt ...

issue with retrieving data from PHP script via ajax

My attempts to use AJAX to call a PHP script have been unsuccessful. I added an echo alert statement in my deleteitem.php script to ensure it was being called, but no matter what I tried, it never executed. Both the PHP script and the JS script calling it ...

My function seems to be functioning perfectly fine in Angular and Express, but for some reason, it's not working in Parse Cloud Code. What could

I am facing an issue with my code where it seems to be stuck. After testing it in both Angular and Express, I realized that the code is only progressing up to a certain point due to the requirement of the Master Key to edit the User table with new data. ...

Tips for organizing a multi-layered object based on an internal value

I am currently facing a challenge in sorting a complex object. Here is the structure of the object: [{ "searchResultProperties": [{ "key": "message_time", "value": 1542088800000 }, { "key": "size_byte AVG", "value": ...

Interactive loading of datalist choices using AJAX in the Firefox browser

I have recently decided to replace the Jquery UI autocomplete function on my website with HTML5 datalists that load dynamic options. After researching this topic extensively, I came across various answers on Stack Overflow, such as How do you refresh an HT ...

The div is populated after the onload event is finished

Currently, my onload event is functioning correctly. However, I am encountering an issue where the second part of the onload event calls another function before the first part is finished. The initial part inserts information into an input field, while th ...

What is the best way to ensure blocking on an AJAX call?

When it comes to Ajax, callbacks are used due to its asynchronous nature. I desire my request to the remote URL to wait until a response is received, akin to how Ajax operates, but without the asynchrony. In other words, I seek to create a JAX call. Is t ...

Unable to finish the real-time search request

Coding Challenge <form [formGroup]="searchForm" onsubmit="return false" id="searchField" ng-submit="" \"> <input type="text" placeholder="Search" formControlName="search" (keyup)="updateQuery()"/> <li *ngFor="let product o ...

Parsing a JSON string array in Swift without prior knowledge of the number of strings present

I am trying to parse a JSON object that contains an array with multiple strings, but I am not sure how to proceed. I am familiar with parsing JSON in static methods, but I am unsure about handling multiple strings within an array. This is the structure of ...

Attempting to grasp the sequence in which setTimeout is ordered alongside Promise awaits

I've been puzzling over the sequence of events in this code. Initially, I thought that after a click event triggered and Promise 2 was awaited, the for loop would resume execution once Promise 1 had been resolved - however, it turns out the outcome is ...

Retrieve the values from hidden input fields that share the same name

How do I retrieve values from cName inputs? <form method="post" action=""> <input type="hidden" name="cName" value="test1" /> <input type="submit" name="get" /> </form> <form method="post" action=""> <input type="hi ...

Tips for implementing jQuery plugin in Electron's Renderer Process:

I am currently developing a webview app using Electron. However, I am facing an issue where I cannot load a particular plugin. You can find the plugin at While jQuery seems to be functioning correctly, the plugin is not loading as expected. Can anyone p ...

Vue-Firebase: A guide to linking multiple Firebase services in a single app

I am facing an issue with connecting to two firebases within the same project. In my project, I have two javascript files that connect to each firebase separately, which seems fine. Here is how I import them: import db from '../FireBase' i ...

We're sorry, but the package path . cannot be found within the package's exports

No connection with Firebase due to error(s) in code. File: firebase.js Code: import * as firebase from "firebase" const firebaseConfig = { apiKey: "***", authDomain: "***", projectId: "***", storageBucket: ...

A guide to dynamically adding an HTML class using JavaScript

I have a login page with a text field for email and password, styled using the Bootstrap framework. I want to change the border color of the input field from grey to red when it is empty and the user clicks the login button. I tried implementing the code t ...

Show the helper text when a TextField is selected in Material UI

I would like the error message to only show up when a user clicks on the TextField. Here's my code: import React, { useState, useEffect } from 'react'; import { TextField, Grid, Button } from '@material-ui/core'; const ReplyToComm ...

"Is there a similar function in axios to jquery's ajaxComplete

Just began delving into axios and gotta say, it's pretty awesome! I've got a burning question that I can't seem to find the answer to. Maybe there isn't one? In jQuery ajax, there's this handy method called ajaxComplete. I'm ...

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

We are experiencing difficulties rendering flash messages in Expressjs with Handlebars(hbs) and express-messages using flash-connect

I'm working on an express app and I want to display flash messages when a user signs up using a form. The technologies I am utilizing include Node.js, Express.js, Handlebars(hbs), connect-flash, and express-messages. To make finding errors easier, I ...

Exploring the capabilities of Angular's ngResource library and how it

Currently, I am developing a Twitch app and instead of using $http, I opted for ngresource to explore new possibilities. However, I encountered an issue with the offline tab where the users are visible but their logo or username is not displayed. This happ ...