Alexis San Martin
Alexis San Martin

Reputation: 45

Change number into string in objects - javascript

how can I parse all object values inside of an array of objects into strings? example of my obj:

// my array of objects
[
 {
  prop1: 23123 ---> to "23123"
  prop2: "asda"
  prop3: "cmcmcm22"
  prop4: 23312 ---> to "23312"
  ....
 },
 {
  prop1: 23123 ---> to "23123"
  prop2: "asda"
  prop3: "cmcmcm22"
  prop4: 23312 ---> to "23312"
  ....
 }
 ...
]


// what i tried
obj.forEach( (element: any) => {
        Object.values(element).forEach((value:any) =>{
             if(!isNaN(value)){
                value = value.toString();
             }
           
        })
    });

but the above code doesn't work.

thanks in advance!

Upvotes: 0

Views: 597

Answers (2)

Andy
Andy

Reputation: 63524

map over the object, and then map over each object's entries, and return a stringyfied value if the value is a number.

const data = [
 {
  prop1: 23123,
  prop2: "asda",
  prop3: "cmcmcm22",
  prop4: 23312
 },
 {
  prop1: 23123,
  prop2: "asda",
  prop3: "cmcmcm22",
  prop4: 23312
 }
];

const res = data.map(obj => {
  return Object.entries(obj).map(([key, value]) => {
    return {
      [key]: Number.isNaN(value) ? value : value.toString()
    };
  });
});

console.log(res);

Upvotes: 0

vsemozhebuty
vsemozhebuty

Reputation: 13792

In order to change object values, you need to get object keys:

const obj = [
 {
  prop1: 23123,
  prop2: "asda",
  prop3: "cmcmcm22",
  prop4: 23312,
 },
 {
  prop1: 23123,
  prop2: "asda",
  prop3: "cmcmcm22",
  prop4: 23312,
 },
];


obj.forEach((element) => {
  Object.keys(element).forEach((key) =>{
    if(!isNaN(element[key])){
      element[key] = element[key].toString();
    }
  })
});

console.log(obj);

Upvotes: 2

Related Questions