Вы можете сделать это несколькими способами:
- Используя простой
for..of
цикл - Используя
.replace()
(сохраняет форматирование исходной строки) - Использование метода отображения (например:
.map
- Переход за борт с рекурсией + троичные ...
- Использование циклов:
const months={jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};
const input = "jan,dec,feb";
const dates = input.split(','); // turn your input into an array
let converted = "";
for(let month of dates) { // loop through each month in dates
if(month in months) { // check if the month is a key in months
converted += months[month] +','; // add number version to converted sring
} else { // if the month isn't in the converted month object, then no need to convert it
converted += month+','; // add month to (ie the number) to the converted output
}
}
console.log(converted.slice(0, -1)); // using slice(0, -1) to remove trailing comma
Использование
.replace()
для сохранения исходного форматирования:
const months={jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};
let input = "jan, dec, feb, 5";
const dates = input.split(','); // turn your input into an array
for(let month of dates) {
month = month.trim();
if(month in months) {
input = input.replace(month, months[month]);
}
}
console.log(input);
Использование
map
.Здесь функция внутренней стрелки вызывается для каждого
month
, а затем преобразуется в соответствующее значение в объекте
months
.Затем мы используем
.join(',')
, чтобы объединить массив значений:
const months={jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};
const input = "jan,dec,feb";
const converted = input.split(',')
.map((month) => month in months ? months[month] : month)
.join(',');
console.log(converted);
Использование рекурсии с троичным оператором:
const months={jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"};
const input = "jan,dec,feb";
const res = (f = ([m, ...rest]) => m && m in months ? months[m]+','+f(rest) : m ? m+','+f(rest) : '')(input.split(',')).slice(0,-1);
console.log(res);