2

I have these results from calling a function in javascript:

(1, 00), (2, 10), (3, 01), (4, 11)

I want to assign that in an array or json format that will result like this:

[{id:1, number: 00},{id:2, number: 10},{id:3, number: 01},{id:4, number: 11}]

Or anything that will result an array lenght of 4

Is that possible? Please help. Thanks :)

4
  • 1
    is the result a string? or what data structure is it? have you tried anything? Commented Feb 10, 2017 at 8:09
  • 1
    Of course it's possible, you just have to write the program to do it. Commented Feb 10, 2017 at 8:09
  • Use .split() with a delimiter of ), to find each pair. Then split that up with a delimiter of , to find each number in the pair. Commented Feb 10, 2017 at 8:11
  • The result was in string format @NinaScholz Commented Feb 10, 2017 at 8:12

2 Answers 2

3

Use regex to get the pattern and generate the array based on the matched content.

var data = '(1, 00), (2, 10), (3, 01), (4, 11)';

// regex to match the pattern
var reg = /\((\d+),\s?(\d+)\)/g,
  m;
// array for result
var res = [];
// iterate over each match
while (m = reg.exec(data)) {
  // generate and push the object
  res.push({
    id: m[1],
    number: m[2]
  });
}

console.log(res);


Or by splitting the string.

var data = '(1, 00), (2, 10), (3, 01), (4, 11)';

var res = data
  // remove the last and first char
  .slice(1, -1)
  // split the string
  .split(/\),\s?\(/)
  // iterate over the array to generate result
  .map(function(v) {
    // split the string 
    var val = v.split(/,\s?/);
    // generate the array element
    return {
      id: val[0],
      number: val[1]
    }
  })

console.log(res);

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

Comments

0

Beside the other splitting solution, you could use String#replace and replace/add the wanted parts for a valid JSON string and use JSON.parse for parsing the string for an object, you want.

var data = '(1, 00), (2, 10), (3, 01), (4, 11)',
    json = data.replace(/\(/g, '{"id":').replace(/,\s?(?=\d)/g, ',"number":"').replace(/\)/g, '"}'),
    object = JSON.parse('[' + json + ']');

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

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.