我有以下字符串:
const str = "Tuba|203488|Music Theory|301071"
我想把它转换成一个对象数组,像这样:
[
{specialty: "Tuba",
userid:203488},
{specialty: "Music Theory",
userid:301071}
]
我如何在javascript中做到这一点?
下面是一个基于这些假设的解决方案:
输入字符串中的- 值用
|
分隔 - 值由两个组成,第一个是
specialty
(字符串值),第二个是userid
(数值) - 结果应该是格式为:
[{ specialty: String, userid: Number }]
的对象数组。
解决方案首先在|
上分割输入字符串,然后使用.reduce()
构建结果对象数组:
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);
输出:
[
{
"specialty": "Tuba",
"userid": 203488
},
{
"specialty": "Music Theory",
"userid": 301071
}
]
您可以通过管道分割字符串,然后在结果数组上进行迭代,递增2,将一个对象添加到最终结果数组:
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);
你可以这样做:
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' }
// ]
您可以这样做。
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);