Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person

Categories

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


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

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share

548k questions

547k answers

4 comments

32.3k users

...