Parse the value of a JSON object from a string within an array and convert it to a number using float

I have an array containing JSON objects. Some of the properties' values in these objects need to be converted from strings to numbers. The goal is to create a new list with the modified JSON objects that have the number values. I attempted to use parseFloat for this task, but it was not successful. code

var json = [{
    "id" : "0", 
    "msg"   : "hi",
    "cost" : "250.24",
    "discount": "10"
},
{
    "id" : "1", 
    "msg"   : "there",
    "cost" : "45.00",
    "discount": "0"
}];

var  json1 = [];

for (var key in json) {
       if (json.hasOwnProperty(key)) {
    
          for (const prop in json[key]) {        
          const parsed = parseFloat(json[key][prop]);              
          res[key][prop] = isNaN(parsed) ? json[key][prop] : parsed;                                        
           //  need to  push  array of modified json object value converted to number from string into json1  
          }
         
       }
    }

Answer №1

your loop seems to be incorrect.

for (var key in json) => if you are looping over an array, it will return the item index instead of the key

json.hasOwnProperty(key) => since your json is actually an array, there is no need to use hasOwnProperty which is typically used for object

I have provided 2 alternatives for you:

*: you can use + to convert a string to a number.

*: if you wish to iterate over item keys, you can utilize way1 and explore methods like Object.entries, Object.keys, and Object.values.

const json = [{
    "id": "0",
    "msg": "hi",
    "cost": "250.24",
    "discount": "10"
},
{
    "id": "1",
    "msg": "there",
    "cost": "45.00",
    "discount": "0"
}];

//way1
const json1 = json.map((item)=>{
    return Object.entries(item).reduce((pre,[key,value])=>{
        const parsed = +value
        pre[key] = isNaN(parsed) ? value : parsed
        return pre
    },{})
})
console.log('json1',json1)

//way2
const json2 = json.map((item)=>{
    return {
        "id": +item.id,
        "msg": item.msg,
        "cost": +item.cost,
        "discount": +item.discount,
    }
})
console.log('json2',json2)

Answer №2

Objects Transformation

I find using a map function for object transformation more efficient:

var json = [{
    "id": "0",
    "msg": "hi",
    "cost": "250.24",
    "discount": "10"
  },
  {
    "id": "1",
    "msg": "there",
    "cost": "45.00",
    "discount": "0"
}];

const transformedJson = json.map(obj =>
  Object.fromEntries(Object.entries(obj).map(([key, value]) => {
    const parsedValue = parseFloat(value);
    return [
      key,
      isNaN(parsedValue) ? value : parsedValue
    ];
  }));

console.log(transformedJson);

If you prefer traditional loops:

var json = [{
    "id": "0",
    "msg": "hi",
    "cost": "250.24",
    "discount": "10"
  },
  {
    "id": "1",
    "msg": "there",
    "cost": "45.00",
    "discount": "0"
}];

const transformedJson = [];

for (const obj of json) {
  const mappedObj = {};

  for (const [key, value] of Object.entries(obj)) {
    const parsedValue = parseFloat(value);
    mappedObj[key] = isNaN(parsedValue) ? value : parsedValue;
  }

  transformedJson.push(mappedObj);
}

console.log(transformedJson);

Arrays Conversion

var json = [[
    {key:"id", value:"0"},
    {key:"msg", value:"hi"},
    {key:"cost", value:"250.24"},
    {key:"discount", value:"10"}
  ],
  [
    {key:"id", value:"1"},
    {key:"msg", value:"there"},
    {key:"cost", value:"45.00"},
    {key:"discount", value:"0"}
]];

const convertedJson = json.map(obj =>
  obj.map(({key, value}) => {
    const parsedValue = parseFloat(value);
    return {
      key,
      value: isNaN(parsedValue) ? value : parsedValue
    };
  });

console.log(convertedJson);

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

Making Jquery data tables editable for cells

After spending the last 4 hours tinkering with this, I have hit a wall and can't seem to make any progress. I am attempting to use the jquery datatable featured in this link: http://datatables.net/examples/api/editable.html (a widely used plugin). I h ...

Eliminating the table header in the absence of any rows

I have successfully implemented a Bootstrap table in my React application, where users can add or delete rows by clicking on specific buttons. However, I want to hide the table header when there are no rows present in the table. Can anyone guide me on how ...

Use PHP to create a new JSON file on the server by submitting a form, then utilize a second form to update

My current goal is to create a json file using a form and then update that file with another form. Both of these processes are handled in the process.php file. I have managed to successfully update the json file if it is named as data.json initially in pro ...

Retrieval of components from JSON array of objects

I have a JSON array containing objects stored on the server. How can I access the first object to print its contents? The data is in the following format: [ { "eventId": "8577", "datasetId": "34", "nodeId": "8076", "typeId": "4", "type": ...

Is there a hashing algorithm that produces identical results in both Dart and TypeScript?

I am looking to create a unique identifier for my chat application. (Chat between my Flutter app and Angular web) Below is the code snippet written in Dart... String peerId = widget.peerid; //string ID value String currentUserId = widget.currentId ...

Double Serialization with Java's Jackson Library

In my code, I have a class that includes a String field and a Map field. My goal is to serialize this class into JSON using Jackson. public class Mapping private String mAttribute; @JsonIgnore private Map<String, String> mMap; @J ...

Filtering properties of objects in Vue

I am currently dealing with an array of objects that represent continents: data() { return { continents: [ { name: "South America", countries: [ { name: "P ...

Transmit data from a child to parent component in React

As I dive into tutorials and delve into the documentation, I am embarking on setting up my first react project to gain a deeper understanding of its functioning. Being a novice in this realm, I sense that a key concept eludes me. The challenge I face lies ...

Getting dynamic variables in the `getStaticProps` function of NextJS can greatly enhance

I am working on utilizing getStaticProps in order to fetch data based on a variable. Here is a sample code snippet: export async function getStaticProps() { const res = await fetch(localWordpressUrl, { method: 'POST', headers: { 'C ...

Is there a way to append a key to a value within a JSON object that is currently missing a key identifier?

How can I add a key to a value in a JSON object using React? The JSON I have currently has a value without a key, making it difficult to read. I've tried using JSON.Stringify and the replacer function, but they didn't solve my issue. Deleting the ...

What is the best method for comparing the keys and values of two arrays?

I'm facing a challenge with two arrays that have similar keys and values. My goal is to create a new array containing only the values that are not present in the first array. I attempted to use the array_intersect function, but the outcome was unexpec ...

What is the best way to create an HTML5 Range that gracefully degrades?

I want to incorporate the <input type='range' /> element from HTML5 for modern browsers and fallback to a <select /> if needed. Since I am working with Ruby-on-Rails, as a last resort, I could implement something similar to this on th ...

Is it possible to utilize a designated alias for an imported module when utilizing dot notation for exported names?

In a React application, I encountered an issue with imports and exports. I have a file where I import modules like this: import * as cArrayList from './ClassArrayList' import * as mCalc1 from './moduleCalc1' And then export them like t ...

Loop through the CSS classes and add a number to the end of each class using JavaScript

I need to configure a form in SharePoint 2010 where certain fields are conditionally required. I have managed to set this up, but now I want a visual indicator on the form to show which fields are required. Not Required: field Required: field* My curren ...

Having trouble setting a background image for a specific DIV element in HTML

I am in the process of updating my webpage, and need some assistance implementing a small background image. Here is what I have done so far: https://i.sstatic.net/nTxtD.png Below is the marked section where I am trying to add the background image: https ...

Initiating an AJAX call with custom headers

According to David Flanagan's book "JavaScript: The Definitive Guide, 5th Edition", it is recommended to send request headers before making an AJAX request. Is it necessary to do this for compatibility across different browsers? request.setRequestHe ...

What do I need to verify? An uncaught TypeError has occurred in the promise, indicating that the property 'MyFunctionName' cannot be read from an undefined URL

The issue arises solely in the compiled application, leading me to believe it's a browser-specific problem. However, I'm uncertain: I've inserted the following script into a webpage: async function exportChatAsXMLHelper(params){ let dis ...

How to implement the Ionic ToastController without being confined to a Vue instance

I am currently facing a challenge while trying to utilize the ToastController of Ionic outside a vue instance. I have created a separate actions file which will be loaded within the vue instance, handling a request. Within this request, certain validations ...

Solving the AJAX POST Error 404 with the power of javascript, MySQL, and PHP

I want to build a dynamic search bar that fetches results from my database as I type in names. https://i.sstatic.net/P4GLs.png Here's the layout of my project: https://i.sstatic.net/y5svt.png The main files involved are map.js, where I handle the ...

Looking to organize my divs by data attributes when clicked - how can I achieve this with javascript?

I am looking to implement a dropdown sorting functionality for multiple divs based on different data attributes such as price and popularity. The specific divs are labeled as "element-1" and are contained within the "board-container". var divList = $(". ...