Reputation: 85
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,
}
]
Upvotes: 1
Views: 328
Reputation: 26370
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()
Upvotes: 2