How can I convert string to array of objects in JavaScript
You could split and iterate the array.
const
string = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true',
result = [];
for (let i = 0, a = string.split('|'); i < a.length; i += 2) {
const
option = a[i],
value = JSON.parse(a[i + 1]);
result.push({ option, value });
}
console.log(result);
You can use .match()
on the string with a regular expression to get an array of the form:
[["Option 1", "false"], ...]
And then map each key-value into an object like so:
const str = "Option 1|false|Option 2|false|Option 3|false|Option 4|true";
const res = str.match(/[^\|]+\|[^\|]+/g).map(
s => (([option, value]) => ({option, value: value==="true"}))(s.split('|'))
);
console.log(res);
const options = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true';
const parseOptions = options => options.split('|').reduce((results, item, index) => {
if (index % 2 === 0) {
results.push({ option: item });
} else {
results[results.length - 1].value = item === 'true';
}
return results;
}, []);
console.log(parseOptions(options));