简体   繁体   中英

Change typeof for specific keys for each object in json array

I have the following Javascript array, that contains JSON objects with 4 keys (team, pts, asts, rebs):

[
  {
     team: "A", 
     pts: "24",
     asts: "17",
     rebs: "14"
  },
  {
     team: "B", 
     pts: "24",
     asts: "11",
     rebs: "13"
  },     
  {
     team: "C", 
     pts: "14",
     asts: "27",
     rebs: "24"
  }
];

For some reason the pts , asts , and rebs data is all coming in as strings, whereas I need these to be numbers. Is there an easy way to specify an array of key names ["pts", "asts", "rebs"], and have the values for those key names convert from strings to numbers?

Been struggling with this for longer than I'd like to admit, any help is appreciated!

You can use map and reduce to handle this:

 const arr = [ { team: "A", pts: "24", asts: "17", rebs: "14" }, { team: "B", pts: "24", asts: "11", rebs: "13" }, { team: "C", pts: "14", asts: "27", rebs: "24" } ]; const result = arr.map(el => Object.keys(el).reduce((acc, curr) => ({ ...acc, ...curr === 'team' ? {[curr]: el[curr]} : {[curr]: Number(el[curr])}, }), {})); console.log(result); 

You can simply loop through the keys of object and convert them to numbers if they are of numeric value.

This can be accomplished by creating a simple function that does such a conversion and passing it to the map over the input data:

const input=[{team:"A",pts:"24",asts:"17",rebs:"14"},{team:"B",pts:"24",asts:"11",rebs:"13"},{team:"C",pts:"14",asts:"27",rebs:"24"}];

function convertStringKeysToNum(obj) {

    return Object.keys(obj).reduce((all, key) => {
        all[key] = Number(obj[key]) || obj[key];
        return all;
    },{})

}

const result = input.map(convertStringKeysToNum);

console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM