I have an array of weekday indices (consisting of the numbers 0-6) that need to be converted to the appropriate corresponding 3-letter weekday strings.
For instance, the array [0, 1, 2, 3, 4, 5, 6]
should be converted to ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
, and [2,4]
should be converted to ["Wed","Fri"]
. This is my given input data:
"data":[
{
"name":"John",
"gender":"M",
"age":"40",
"days_present":[0,1,2,3,4,5,6],
"time_spend":1626908399000
},
{
"name":"Maria",
"gender":"F",
"age":"32",
"days_present":[2,6],
"time_spend":1626908366000
},
{
"name":"Ben",
"gender":"M",
"age":"27",
"days_present":[2,4,6],
"time_spend":1626908331000
}
]
And the resultant data should appear as follows:
"data":[
{
"name":"John",
"gender":"M",
"age":"40",
"days_present":["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
"time_spend":1626908399000
},
{
"name":"Maria",
"gender":"F",
"age":"32",
"days_present":["Wed","Sun"],
"time_spend":1626908366000
},
{
"name":"Ben",
"gender":"M",
"age":"27",
"days_present":["Wed", "Fri","Sun"],
"time_spend":1626908331000
}
]
How should I best go about doing this?
CodePudding user response:
Pretty simple, just do two map
calls:
const obj={"data":[{"name":"John","gender":"M","age":"40","days_present":[0,1,2,3,4,5,6],"time_spend":1626908399000},{"name":"Maria","gender":"F","age":"32","days_present":[2,6],"time_spend":1626908366000},{"name":"Ben","gender":"M","age":"27","days_present":[2,4,6],"time_spend":1626908331000}]};
const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const result = obj.data.map(({ days_present, ...r }) => ({
days_present: days_present.map(i => weekdays[i]),
...r
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: auto; }
This loops over each item in data
and converts each of the weekday indices to their corresponding weekday string.