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?
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);
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' }
// ]
Here is a solution making these assumptions:
|
specialty
(string value), the second one the userid
(number value)[{ 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
}
]
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.