I have a string set of -
"uid:ID1,name:Name1,uid:ID2,name:Name2"
I want to map "uid:ID1,name:Name1" into
The following format
{
uid :'ID1',
name: "Name1"
}
But for it to make as many property sets as are passed in via the string set.
So for the input string with "2 sets" I need it to make this following output.
{
uid :'ID1',
name: "Name1"
},
{
uid :'ID2',
name: "Name2"
}
What can I try?
halfer
20.2k20 gold badges111 silver badges208 bronze badges
2 Answers 2
Use the main function below:
const main = str => {
// split on each comma
const arr = str.split(',');
// put back elements by pairs
const pairs = [];
for (let i=0; i<arr.length; i+=2) {
let o = {};
o.uid = arr[i].split(':')[1];
o.name = arr[i+1].split(':')[1];
pairs.push(o);
}
return pairs;
}
console.log(main('uid:ID1,name:Name1'));
console.log(main('uid:ID1,name:Name1,uid:ID2,name:Name2'));
This assumes that the input string is well-formed as a repetition of uid:...,name:... (no arbitrary key, no optional key) joined by ,.
answered Jul 14, 2019 at 11:49
Nino Filiu
19k11 gold badges65 silver badges97 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Assuming that you want Objects and the keys are arbitrary...
console.log(
"uid:ID1,name:Name1,uid:ID2,name:Name2"
.split(/[,:]/)
.reduce((res, val, i, arr) => {
if (i % 4 === 0) {
res.push({})
}
if (i % 2) {
res[res.length - 1][arr[i - 1]] = arr[i]
}
return res
}, [])
);
Comments
lang-js