Welcome to OGeek Q&A 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...