Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert string to array of objects in JavaScript

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
  }
]
like image 522
Muhammad Fazeel Avatar asked Sep 02 '20 06:09

Muhammad Fazeel


4 Answers

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);
like image 95
Nina Scholz Avatar answered Jan 04 '23 13:01

Nina Scholz


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);
like image 39
Nick Parsons Avatar answered Jan 04 '23 12:01

Nick Parsons


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));
like image 24
Adrian Brand Avatar answered Jan 04 '23 13:01

Adrian Brand


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)
like image 25
Amir Hussain Avatar answered Jan 04 '23 13:01

Amir Hussain