Changing a string to an integer within an array using JavaScript

I am working with an array displayed by console.log(temp) in the following format:

temp = [{name: "Request A", data: "1"}
       {name: "Request B", data: "12"}
       {name: "Request C", data: "6"}]

If I want to change the format of my array to look like this:

 temp: [{name: "Request A", data: [1]}
       {name: "Request B", data: [12]}
       {name: "Request C", data: [6]}]

I need some assistance in achieving this. Thank you.

Answer №1

To create a new array, utilize the map function and use parseInt to convert strings to numbers.

let exampleArray = [{
    title: "Item A",
    value: "1"
  },
  {
    title: "Item B",
    value: "12"
  },
  {
    title: "Item C",
    value: "6"
  }
]
let newArray = exampleArray.map((element) => {
  return {

    title: element.title,
    value: [parseInt(element.value, 10)]
  }


});
console.log(newArray)

Answer №2

If you want to make changes directly to the array, you can iterate through each item using forEach and update the desired property:

let values = [ {name: "Item A", data: "3"},
             {name: "Item B", data: "17"},
             {name: "Item C", data: "8"}]

values.forEach(element => element.data = [+(element.data)])
console.log(values)

Answer №3

Give this a shot!

arr = [{title: "Task X", value: "5"},
       {title: "Task Y", value: "19"},
       {title: "Task Z", value: "8"}];


  let newArr = arr.map(item => {
    item.value = [parseInt(item.value)]
    return item;
  })

  console.log(newArr);

RESULT:

[ { "title": "Task X", "value": [ 5 ] }, { "title": "Task Y", "value": [ 19 ] }, { "title": "Task Z", "value": [ 8 ] } ]

Answer №4

To achieve this, simply utilize the map function.

let example =  [{name: "Request A", data: "1"},{name: "Request B", data: "12"},{name: "Request C", data: "6"}]

let result = example.map(item => {
  return {
    ...item,
    data : [+item.data]
  }
})

console.log(result)

Answer №5

Check out this code snippet - I utilized Array.of method to generate an array and the + operator to convert a string into an array.

temp.map(t => (t.data = Array.of(+t.data), t));

Answer №6

Experiment

temp.forEach(item=> item.value=[+item.value]);

let temp = [{title: "Task A", value: "7"},
       {title: "Task B", value: "15"},
       {title: "Task C", value: "9"}];
       
       
temp.forEach(item=> item.value=[+item.value]);

console.log(JSON.stringify(temp));

Answer №7

If you want to achieve this result, you can utilize the following code snippet in a node REPL environment.

> let initialArray = [{name: "Request A", data: "1"}, {name: "Request B", data: "12"}, {name: "Request C", data: "6"}];
undefined
> initialArray.forEach(function(item) {
..... item.data = [parseInt(item.data, 10)];
..... });
undefined
> initialArray
[ { name: 'Request A', data: [ 1 ] },
  { name: 'Request B', data: [ 12 ] },
  { name: 'Request C', data: [ 6 ] } ]
>

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

Triggering a function without the presence of an actual event

I need to come up with a solution for reusing a function triggered by an event binding. This problem stems from browsers remembering checkbox states, which is why I have to call the function on document load. One approach could involve wrapping setGrid() ...

Sending a JSON array to a WebMethod

I encountered an issue when attempting to convert an object to a JSON array as a string, resulting in an Internal Server Error. Fortunately, the GetServerTime method is functioning properly. My goal is to send an array of objects to the server and conver ...

AngularJs: The ability to rate or rate functionality

I've been attempting to incorporate a likes/dislikes feature into my project, but it doesn't seem to be functioning correctly. As someone new to this type of functionality, I could use some guidance. Below is the snippet of code that outlines wh ...

What is the best way to link this to a function in AngularIO's Observable::subscribe method?

Many examples use the Observable.subscribe() function in AngularIO. However, I have only seen anonymous functions being used like this: bar().subscribe(data => this.data = data, ...); When I try to use a function from the same class like this: update ...

Can TSLint and ESLint give a warning when a function is accessed as a property?

There have been instances where I've made this specific mistake, and I'm curious if there are any ESLint or TSLint rules in place that could detect it. if (this.isBrowser && this.imageURL) {.....} private isBrowser(): boolean{ retur ...

Guide to accessing and updating data in various tabs within a Google spreadsheet

I have two tabs named TAB A and TAB B. My goal is to iterate through TAB A and extract a set of values that I can then paste into TAB B. However, I encountered an error message saying, "Cannot read property 1, etc" function getValuesFromModal(form) { ...

Utilizing JavaScript to implement conditional if-else statements on CSS properties

I am trying to implement conditions on CSS properties in JavaScript. What is the most efficient approach to achieve this? <html> <head> <title>TOOLTIP USING JAVASCRIPT</title> <style> span{ curso ...

Apply CSS styles to a group of elements retrieved from an object

How can I apply CSS properties to each element in a collection using jQuery? const cssProperties = { "color": "#555555", "font-weight": "bold", "text-align": "left" }; const $tdCollection = $("tr:first-child").find("td:nth-child(2)"); // Co ...

Can a star rating be generated from a JSON value?

I'm curious if it's possible to display a glyphicon-star based on the value in a JSON file using AJAX. Here is an example of my JSON file: [ { "star": 4 },{ "star": 3 },{ "star": 5 } ] Here is my AJAX code: $(function($){ ...

Using an image URL in a MongoDB database - a step-by-step guide

I am working on a cosmetics project website and need to create product information for each item. Each product will have an image, which I want to include by creating a URL for it and using EJS. For example, to display the image for a product, I would us ...

What are the differences between ajax loaded content and traditional content loading?

Can you explain the distinction between the DOM loaded by AJAX and the existing DOM of a webpage? Is it possible to load all parts of an HTML page via AJAX without any discrepancies compared to the existing content, including meta tags, scripts, styles, e ...

What are the steps to troubleshoot and resolve validation errors while using the paypal-rest-sdk?

I'm currently experimenting with the paypal-rest-sdk to learn how to integrate PayPal checkout into my website. However, I've encountered an issue during testing where whenever I click submit in my form, I receive a "localhost refused to connect" ...

I have saved a text file on my device and now I am looking to showcase its contents on an HTML webpage using JavaScript, rather than downloading

I have been working on converting a PDF document into a base64 string. After successfully converting it and saving it to a text file, I am currently able to download the text file. However, I do not want users to have to download the file, but rather dis ...

javascript - The Key Pair of a Jquery Object is Not Defined

I'm currently going through an HTML element, which is an input field using jQuery, but I keep encountering an error. Here's the code snippet: $(".submit_button").on("click touch", function(e){ e.preventDefault(); var formdat ...

What is the best way to arrange this by DateTransaction using a dropdown list?

Requesting assistance from the PHP community! I'm a newbie and in need of your expertise. My task is to create a dropdown list that sorts a table based on the DateTransaction column, with options ranging from January to December. Here is the code sni ...

Refresh the content of a webpage in AngularJS without the need to fully reload the entire page

Within my controller and view files, I have content that is sourced from various places, including API calls. For instance, I have information retrieved from the database where users can update certain details like their last name. After submitting the up ...

Implementing a dual hover effect on a Div element

I am working with HTML code that includes an image and text <div class="subcontainer1"> <img src="a.png" alt="" class="imgcolumn"> <h3 class="header3">Hello</h3> </div> This setup places the content above the image. ...

Adding array elements into a mysql database

The array values containing variables are being passed from a previous page. When I use print_r($values), the entire value of the array is displayed, including the numerical indices (e.g. array[0], array[1], etc.). If someone could please advise me on what ...

Retrieve data from a specific field in a JSON response

I am attempting to retrieve a specific field from an API request, which will be utilized for another task. My goal is to automate this request in order to keep track of the timestamp of the remote machine. Here is the script I have created to obtain the j ...

Techniques for Extracting the Values of all ng-models within an ng-repeat Loop

How do I retrieve the total value of all ng-models within an ng-repeat loop using AngularJS? Below is my HTML code: <div ng-repeat="kind in plans.availableOptions"> <span class="payLabel text-left">{{kind.name}}</span> ...