1

Fellow Javascript developers, how do I change a property's value from Int/Double to String for all the objects in an array?

Original Array

data = [
  Object {
    "id": 2138,
    "name": "Steve",
    "email": "[email protected]",
    "phone": 8745235698,
    "addressLine1": "Some Nice Address",
    "shopId": 115,
  },
  Object {
    "id": 2139,
    "name": "Chris",
    "email": "[email protected]",
    "phone": 9865345689,
    "addressLine1": "Vhjhjg",
    "shopId": 115,
  },
  Object {
    "id": 2140,
    "name": "Melinda",
    "email": "[email protected]",
    "phone": 9867626833,
    "addressLine1": "California",
    "shopId": 115,
  }
]

I have a Multipicker Library which needs the id property to be a String Value when I pass the array to it. When the id is not a String, I don't see any data in the library to select.

I've tried to use the map() function, but I couldn't retain the object. What I got was only an array of string ids.

//Tried Map Method
let customers = data.map((item) => (item.id = String(item.id)));
console.log("fixed array", customers);

result ["2138","2139","2140"]

I also want to retain the original array, so if possible please provide a solution using the map() function, since it returns a new array without mutating the original one. Or any other method which doesn't mutate the original array

//Expected Result
//id's changed to String

customers = [
  Object {
    "id": "2138",
    "name": "Steve",
    "email": "[email protected]",
    "phone": 8745235698,
    "addressLine1": "Some Nice Address",
    "shopId": 115,
  },
  Object {
    "id": "2139",
    "name": "Chris",
    "email": "[email protected]",
    "phone": 9865345689,
    "addressLine1": "Vhjhjg",
    "shopId": 115,
  },
  Object {
    "id": "2140",
    "name": "Melinda",
    "email": "[email protected]",
    "phone": 9867626833,
    "addressLine1": "California",
    "shopId": 115,
  }
]
2
  • 1
    Just loop over the original array and set thing.id = thing.id.toString(). You don't need to map if you are wanting to mutate the original. Just loop it. Commented Oct 28, 2020 at 14:00
  • 1
    data.forEach(it => it.id = it.id.toString()) Commented Oct 28, 2020 at 14:03

1 Answer 1

2

If you use a map, you must return the modified object :

let customers = data.map( item => {
     item.id = String(item.id);
     return item;
});

But you don't need a map. You can just iterate this way :

data.forEach(item => item.id = String(item.id)) // or "" + item.id, or item.id.toString()
Sign up to request clarification or add additional context in comments.

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.