Reputation: 29
I want to convert the imdb ratings given inside the array of objects watchList. I am trying it using map function but it is not happening. The newList is giving just the old list with no changes whatever. What am I doing wrong?
var watchList = [
{
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
}
];
let newList=[];
newList=watchList.map(function(list){
Number(list.imdbRating);
return list;
});
console.log(newList);
Upvotes: 2
Views: 1692
Reputation: 371019
Just declaring Number
does not mutate the original value. If you want the object's property to have its imdbRating
be a Number, you have to assign it.
var watchList=[{"Metascore":"74","imdbRating":"8.8","imdbVotes":"1,446,708","imdbID":"tt1375666","Type":"movie","Response":"True"},{"Metascore":"74","imdbRating":"8.6","imdbVotes":"910,366","imdbID":"tt0816692","Type":"movie","Response":"True"},{"Metascore":"82","imdbRating":"9.0","imdbVotes":"1,652,832","imdbID":"tt0468569","Type":"movie","Response":"True"}];
watchList.forEach(function(list){
list.imdbRating = Number(list.imdbRating);
});
console.log(watchList);
Note that objects are passed by reference in Javascript - changing something in a reference to an object will change the original object, which is why I used forEach
instead of .map
. If you want to create entirely new objects (and not mutate the original ones), use object spread as well as map
:
var watchList=[{"Metascore":"74","imdbRating":"8.8","imdbVotes":"1,446,708","imdbID":"tt1375666","Type":"movie","Response":"True"},{"Metascore":"74","imdbRating":"8.6","imdbVotes":"910,366","imdbID":"tt0816692","Type":"movie","Response":"True"},{"Metascore":"82","imdbRating":"9.0","imdbVotes":"1,652,832","imdbID":"tt0468569","Type":"movie","Response":"True"}];
const newList = watchList.map(({ imdbRating, ...rest }) => ({
imdbRating: Number(imdbRating),
...rest,
}));
console.log(newList);
Upvotes: 1
Reputation: 504
If you want a quick conversion from string to integer you can use +
operator.
Example :
var newList=[];
newList=watchList.map(function(list){
list.imdbRating = +list.imdbRating;
return list;
});
Upvotes: 0