Search code examples
javascriptarraysjsonmappingjavascript-objects

Convert String into Array of Objects: JS


I have the following string:

const str = "Tuba|203488|Music Theory|301071"

I would like to convert it to an array of objects like so:

[
{specialty: "Tuba",
userid:203488},
{specialty: "Music Theory",
userid:301071}
]

How can I do this in javascript?


Solution

  • Here is a solution making these assumptions:

    • values in input string are separated by |
    • values are in a set of two, the first one is the specialty (string value), the second one the userid (number value)
    • result should be an array of objects of format: [{ specialty: String, userid: Number }]

    The solution first splits the input string on |, then uses a .reduce() to build the resulting array of objects:

    const str = "Tuba|203488|Music Theory|301071";
    
    let result = str.split('|').reduce((acc, val, idx, arr) => {
      if(idx % 2) {
        acc.push({
          specialty: arr[idx - 1],
          userid: Number(val)
        });
      }
      return acc;
    }, []);
    console.log(result);

    Output:

    [
      {
        "specialty": "Tuba",
        "userid": 203488
      },
      {
        "specialty": "Music Theory",
        "userid": 301071
      }
    ]