Home > Mobile >  Convert String into Array of Objects: JS
Convert String into Array of Objects: JS

Time:01-12

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?

CodePudding user response:

You can split the string by the pipe and then iterate over the resultant array, incrementing by 2, adding and object to a final result array:

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

const result = [];

const arr = str.split("|");

for (let i = 0; i < arr.length; i =2) {
  result.push({ specialty: arr[i], userId: arr[i 1] });
}

console.log(result);

CodePudding user response:

You can do like this:

function createArrayFromString(str) {
  const strArray = str.split("|")
  let results = []

  for (let i=0; i<strArray.length; i =2) {
    results.push(
      {
        speciality: strArray[i],
        userid: strArray[i 1]
      }
    )
  }
  return results
}

const str = "Tuba|203488|Music Theory|301071"
console.log(createArrayFromString(str))
// [
//   { speciality: 'Tuba', userid: '203488' },
//   { speciality: 'Music Theory', userid: '301071' }
// ]

CodePudding user response:

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
  }
]

CodePudding user response:

Here's how you can do it.

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

const splitStringArray = str.split("|");
console.log("Split", splitStringArray);
const finalObject = [];
for (let index = 0; index < splitStringArray.length; index  = 2) {
  finalObject.push({
    Speciality: splitStringArray[index],
    UserId: splitStringArray[finalObject   1],
  });
}
console.log("Final Object", finalObject);

  • Related