How to convert pipe-delimited string to an object in JavaScript
If you want to create an object out of a pipe-delimited string in JavaScript, you can use the following split
+ reduce
combination to get the desired effect:
const string = 'year|2022|month|01|day|01';
string.split('|')
.reduce((accumulator, current, index, array) => {
return index % 2 === 0
? Object.assign({ [current]: array[index + 1] }, accumulator)
: accumulator
}, {});
First, we need to split up the string by the pipes to get an array of strings, so we can pair them, therefore:
'year|2022|month|01|day|01' -> becomes ['year', '2022', 'month', '01', 'day', '01']
Then, as a second step, we can use reduce
to populate the values in an empty object. At every second step, we add a new property to the object, using the current
value as the key for the property, and using the value next to it in the array as the value for the key. So this:
['year', '2022', 'month', '01', 'day', '01'] -> becomes { year: '2022', month: '01', day: '01' }
If you would like to reuse this as a function, copy and paste the code below to your codebase:
export const converPipesToObject = string => string.split('|')
.reduce((accumulator, current, index, array) => {
return index % 2 === 0
? Object.assign({ [current]: array[index + 1] }, accumulator)
: accumulator
}, {});
// Later call it like:
converPipesToObject('year|2022|month|01|day|01')
Resources:
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews