This is the string Option 1|false|Option 2|false|Option 3|false|Option 4|true
I want to convert it to array of objects like this
Is This Possible In javaScript Nodejs???? thanks in Advance.
[
{
"option": "Option 1",
"value": false
},
{
"option": "Option 2",
"value": false
},
{
"option": "Option 3",
"value": false
},
{
"option": "Option 4",
"value": true
}
]
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));
str='Option 1|false|Option 2|false|Option 3|false|Option 4|true';
str=str.split('|');
result=[];
for(var i=0;i<str.length;i += 2){
result.push({"option":str[i],"value":str[i+1]=="true"?true:false})
}
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With