Reputation: 6246
I'm trying to map some data, from a string to a boolean (if possible).
Say I have this array (all the values are of type string).
var values = array["1", "0", "0", "1", "SomethingElse"];
I want to map the 1s to true, 0s to value, and SomethingElse just returns itself.
My idea is to have a map object
map = {
1: true,
0: false
};
Then have a wrapper function check if the key is set, if not return itself. Something like this
function mapValue(val) {
return (isset(map[val])) ? map[val] : val;
}
var newValues = [];
angular.forEach(values, function(val, key) {
newValues[key] = mapValue(val);
});
That's my rough plan. Is this a good approach to this problem? Or is there a much simpler way I could do this?
Upvotes: 0
Views: 318
Reputation: 239443
You can use the Array.prototype.map
function, like this
var values = ["1", "0", "0", "1", "SomethingElse"],
map = { 1: true, 0: false };
console.log(values.map(function(currentItem) {
return map.hasOwnProperty(currentItem) ? map[currentItem] : currentItem;
}));
# [ true, false, false, true, 'SomethingElse' ]
Upvotes: 3