Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - How to update a json object request string values to NUMBER in REACT

I have an json object array and I want to update the values from String to Number

Example JSON object

[
   {
      "atest":{
         "value":"0",
         "units":"sqft"
      },
      "etest":{
         "value":"70",
         "units":"inches"
      },
      "waveTest":"8",
      "db_test":{
         "value":"3.7",
         "units":"feet"
      },
      "erp_test":{
         "value":"0.97",
         "units":"feet"
      },
      "erfp_test":"5"
   },
   {
      "atest":{
         "value":"6",
         "units":"sqft"
      },
      "etest":{
         "value":"20",
         "units":"inches"
      },
      "waveTest":"2",
      "db_test":{
         "value":"8.6",
         "units":"feet"
      },
      "erp_test":{
         "value":"2.57",
         "units":"feet"
      },
      "erfp_test":"10"
   }
]

I want to update all the "value": "0" to "value": 0 Please let me know what steps I need to mutate the json object to be able to update every data after "value" to a NUMBER

I seen a simliar post (reference) but his data schema is different compared to mine.

Reference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is the solution. I added comments to the code for understanding.

// original array
const arr = [
   {
      "atest":{
         "value":"0",
         "units":"sqft"
      },
      "etest":{
         "value":"70",
         "units":"inches"
      },
      "waveTest":"8",
      "db_test":{
         "value":"3.7",
         "units":"feet"
      },
      "erp_test":{
         "value":"0.97",
         "units":"feet"
      },
      "erfp_test":"5"
   },
   {
      "atest":{
         "value":"6",
         "units":"sqft"
      },
      "etest":{
         "value":"20",
         "units":"inches"
      },
      "waveTest":"2",
      "db_test":{
         "value":"8.6",
         "units":"feet"
      },
      "erp_test":{
         "value":"2.57",
         "units":"feet"
      },
      "erfp_test":"10"
   }
]

const newArr = arr.map(element => {
  // Object.keys get keys from object by array so you can loop by keys
  Object.keys(element).forEach(key => {
    // check value is exist and parse value string to int
    if (element[key].value) element[key].value = parseFloat(element[key].value)
  })
  // return parsed object to array
  return element
})

console.log(newArr)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...