0

i have array1 form of array and I want to convert it in order to be like array2

const array1 = [
  {name:'sds',long:'23',lat:'22'}, 
  {name:'sdsd',long:'33',lat:'55'}, 
  {name:'sds',long:'44',lat:'66'}
];

const array2 = [
  {name:'sds',long:23,lat:22}, 
  {name:'sdsd',long:33,lat:55}, 
  {name:'sds',long:44,lat:66}
];

basically, I want to change the datatype of longitude and latitude**(java script** ) please If u know do tell me

myckhel
  • 800
  • 3
  • 15
  • 29

3 Answers3

2

Just map over the array and convert string to Number, by appending + to String type will make String type to Number type.

array1.map(({ name, long, lat }) => ({ name, long: +long, lat: +lat }));

const array1 = [
  { name: "sds", long: "23", lat: "22" },
  { name: "sdsd", long: "33", lat: "55" },
  { name: "sds", long: "44", lat: "66" },
];

const result = array1.map(({ name, long, lat }) => ({ name, long: +long, lat: +lat }));
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
1

A crude and brute force way is:

const array1 = [
  {name:'sds',long:'23',lat:'22'}, 
  {name:'sdsd',long:'33',lat:'55'}, 
  {name:'sds',long:'44',lat:'66'}
];


const x  = array1.map(y => {
    // console.log(y);
    y.long = parseInt(y.long);
    y.lat = parseInt(y.lat);
    return y; 
});

console.log(x);

Output will be as expected. It basically maps each item and does the parsing.

Sid
  • 4,893
  • 14
  • 55
  • 110
1

Brother, you can try this. Hope this will help you. Thanks.

const array1 = [
  {name:'sds',long:'23',lat:'22'}, 
  {name:'sdsd',long:'33',lat:'55'}, 
  {name:'sds',long:'44',lat:'66'}
];

const array2 = array1.map(item => ({
  name: item.name,
  long: parseInt(item.long),
  lat: parseInt(item.lat),
}));

console.log(array2)
Showrin Barua
  • 1,737
  • 1
  • 11
  • 22