0

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!

0

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.