I want to convert a string to an object.
My string is something like 7541550448872:1:1:monthly,42397357179112:1.
I want the result to be something like this:
'items': [{
'id': 7541550448872,
'quantity': 1,
"properties": {
"shipping_interval_unit_type": "monthly",
"shipping_interval_frequency": "1"
},
},
{
'id': 42397357179112,
'quantity': 1,
}
]
I was told to use functions like split() and Regex but I could not get it to work. Any idea how to do this?
For me, probably the most preferred method is using Array.split(). You split the array by :, and then construct the JSON by indexing the array. See the code snippet below to see this in action. Also, I'm not sure if you wanted a , between the month and the id or if was just a typo. My code below uses the ,.
const str = '7541550448872:1:1:monthly,42397357179112:1';
const arr = str.split(':');
const json = {
'items': [{
'id': Number(arr[0]),
'quantity': Number(arr[1]),
"properties": {
"shipping_interval_unit_type": arr[3].split(',')[0],
"shipping_interval_frequency": arr[2]
},
},
{
'id': Number(arr[3].split(',')[1]),
'quantity': Number(arr[4]),
}
]
};
console.log(json);
Hoped this helped!