7

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
  }
]
1
  • 2
    I like one liners .... const result = "Option 1|false|Option 2|false|Option 3|false|Option 4|true".split('|').map((option, i, a) => i % 2 ? null : {option, value: a[i+1]}).filter(x => x) Commented Sep 2, 2020 at 7:12

6 Answers 6

15

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);

Sign up to request clarification or add additional context in comments.

1 Comment

It's funny how the Queen of reduce uses a for loop this time. But it might be faster when you skip each second element
4

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);

Comments

3

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));

Comments

2

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)

1 Comment

str[i+1]=="true"?true:false there is no need for a ternary here as str[i+1]=="true" gives the same result
2

I have a slightly more functional solution to the problem, which I think is more semantic

const str = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true';
const parsed = str
    .match(/[^\|]+\|[^\|]+/g)
    .map(matchedValues => {
        const [option, value] = matchedValues.split('|');
        return Object.fromEntries([['option', option], ['value', JSON.parse(value)]]);
    })

console.log(parsed);

1 Comment

Fair enough. I added the JSON.parse but idea is still the same..
0

With Array.prototype.reduce you can morph the array from String.prototype.split into an object.

const str = "Option 1|false|Option 2|false|Option 3|false|Option 4|true";
const arr = str.split('|')

const obj = arr.reduce((carry, elem, index, orig) => {
  if (index % 2) { return carry }
  carry.push({"option": orig[index], "value": !!orig[index+1]});
  return carry;
}, [])

console.log(obj)

Or a more exotic approach with double split

const str = "Option 1|false|Option 2|false|Option 3|false|Option 4|true";
const arr = (str+"|").match(/[^|]+\|[^|]+(?=\|)/g);

const res = arr.reduce((carry, item) => {
  let [option, value] = item.split('|');
  carry.push({option, value: !!value});
  return carry;
}, [])

console.log(res)

1 Comment

@JaromandaX You're right. I edited my answer. Didn't read the OP thoroughly enough

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.