How to convert pipe-delimited string to an object in JavaScript

How to convert pipe-delimited string to an object in JavaScript

Ferenc Almasi β€’ 2022 January 08 β€’ Read time 2 min read
  • twitter
  • facebook
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:

Copied to clipboard! Playground
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:

Copied to clipboard!
'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:

Copied to clipboard!
['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:

Copied to clipboard! Playground
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')
How to convert pipe-delimited string to an object in JavaScript
If you would like to see more webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.