skip to Main Content

I have a problem. I have an abject

let aa = [
    {"x":"1","y":"12"},
    {"x":"2","y":"12"},
    {"x":"3","y":"12"},
    {"x":"4","y":"25"},
    {"x":"5","y":"45"},
    {"x":"6","y":"49"}
]

but I need an object like this

let aa = [
    {"x": 1,"y": 12 },
    {"x": 2,"y": 12},
    {"x": 3,"y": 12},
    {"x": 4,"y": 25},
    {"x": 5,"y": 45},
    {"x": 6,"y": 49}
]

I try to use

Object.keys(a).forEach(function(el){
  i[el] = parseInt(i[el])
 
})
}

but it didn`t help me

2

Answers


  1. You could map the entries with a new type.

    let aa = [
        {"x":"1","y":"12"},
        {"x":"2","y":"12"},
        {"x":"3","y":"12"},
        {"x":"4","y":"25"},
        {"x":"5","y":"45"},
        {"x":"6","y":"49"}
    ],
        result = aa.map(o => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, +v])));
    
    console.log(result);
    Login or Signup to reply.
  2. const aa = [
        {"x":"1","y":"12"},
        {"x":"2","y":"12"},
        {"x":"3","y":"12"},
        {"x":"4","y":"25"},
        {"x":"5","y":"45"},
        {"x":"6","y":"49"}
    ]
    
    const ab = aa.map(a => ({ x: Number(a.x), y: Number(a.y)}))
    

    That will do the job if all the strings are indeed correct numbers, otherwise you have to handle errors somehow.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search