What is the best method for dividing strings in javascript?

After invoking a JavaScript function, I received the following results:

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

I am looking to store this data in an array or JSON format like this:

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

Any suggestions on how I can achieve this and end up with an array of length 4?

If you have any ideas, please share. Thank you! :)

Answer №1

Extract patterns using regex and create an array based on the matched content.

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

// use regex for pattern matching
var reg = /\((\d+),\s?(\d+)\)/g,
  m;
// store results in an array
var res = [];
// loop through each match
while (m = reg.exec(data)) {
  // generate and add objects to the array
  res.push({
    id: m[1],
    number: m[2]
  });
}

console.log(res);


Alternatively, split the string to achieve the same result.

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

var res = data
  // remove parentheses from start and end
  .slice(1, -1)
  // split the string into parts
  .split(/\),\s?\(/)
  // map over the array for processing
  .map(function(v) {
    // split each part
    var val = v.split(/,\s?/);
    // create array elements
    return {
      id: val[0],
      number: val[1]
    }
  })

console.log(res);

Answer №2

Another method to split the string is by using the String#replace function and replacing or adding the necessary parts to create a valid JSON string. You can then use JSON.parse to parse the string into an object.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a "MissingSchemaError" while attempting to populate the database with mongoose-seeder

I am facing an issue while trying to populate a database using mongoose-seeder. Despite setting up the schema correctly, I keep encountering a MissingSchemaError which has left me puzzled. Here is a snippet from the file where I define the schema: const m ...

Create a visual representation of an item within a framework using an Angular directive

I am interested in using a directive to draw a triangle above a series of div elements. In my scenario, I have four squares and two values: charge and normal. The value of charge determines the color of the squares, while normal is used for drawing the t ...

Query to retrieve specific JSON elements

Here is a snippet of JSON data: {"response":[2939, {"mid":6581,"date":1345018696,"out":0,"uid":84175314,"read_state":1,"title":" ... ","body":"Text1"}, {"mid":6578,"date":1344984256,"out":0,"uid":32438192,"read_state":1,"title":" ... ","body":"Text2"} ]} ...

Why does attempting to access an undefined property not trigger an error?

I am curious to know why var myVar = unDef; may trigger a ReferenceError, while var myObj = {}; var myVar = myObj.unDef; runs smoothly? It simply returns undefined without any runtime issues. Despite both not being defined. ...

Constantly showing blank white pages on my website specifically in Internet Explorer 11

I successfully developed a website using react, babel, webpack, and backend Django framework. Everything runs smoothly on Chrome, Safari, and Firefox, but when it comes to IE11, issues arise. Initially, the site functions properly, but after navigating thr ...

Default Selection Issue with Radio Buttons in AngularJS

I am currently encountering an issue with the code snippet included in my directive template '<li ng-repeat="f in foos">' + '<input type="radio" ng-change="foo(f.key)" ng-model="selectedFoo" name="foos" id="{{f.key}}" value="{{f.ke ...

How can I save files to the ~/Documents directory using Node.js on my Mac computer?

Trying to work with the user's Documents folder in Node.js on macOS: var logger = fs.createWriteStream('~/Documents/somefolderwhichexists/'+title+'.txt'); Encountering an error without clear cause. Error message received: Unca ...

Changing the old state in React js: A step-by-step guide

I have a collection of Faq elements. Clicking on a question should display the answer for that specific question while hiding all other answers. The issue I'm facing is that even though it displays the answer for the clicked question, it fails to hi ...

Adding turbolinks to an HTML document can be achieved without the need for a

Recently delving into the world of turbolinks, I discovered that it can be employed independently without relying on a client-side javascript framework. Eager to test this out, I created a bootstrap 4 template and attempted to install it. Firstly, I downl ...

Managing toggles for save and edit buttons in Vue - a comprehensive guide

I am currently working on a Vue 'app' within a larger Django application as a means to enhance my understanding of Vue. My objective is to create unique forms that can be edited independently. I have been experimenting with this for some time n ...

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

Locate a user within an array in Angular 5 by inputting a specific character into a textarea before initiating the search

I'm currently facing a situation with my textarea component... <textarea [(ngModel)]="message" id="commentBox" placeholder="Add your comment here..."></textarea> Additionally, I have a user list that retrieves data from an external API l ...

What is causing my vue.js table to not display properly?

Struggling to render a table using vue.js? You're not alone. Many developers face challenges when trying to use v-for to iterate through data and display it in a table format. It can be frustrating when everything seems fine in the console, but the ta ...

Combine numerous JSON files into a single JSON file

I have numerous JSON files that look like this: For example: 1.json {"name": "one", "description": "testDescription...", "comment": ""} test.json {"name": "test", "description": "testDescription...", "comment": ""} two.json {"name": "two", "descript ...

Move and place, editing tools

Is it possible to create a drag-and-drop editor similar to the one found in the form editor on wufoo.com? ...

Ways to hide the value from being shown

I have integrated jscolor (from jscolor) to allow users to pick a color with an input field. However, I am facing issues in styling it as I'm unable to remove the hex value of the selected color and couldn't find any relevant documentation on av ...

Tips for utilizing innerHeight for a div during both window loading and resizing tasks?

I'm currently working on calculating the top/bottom padding of a div (.content) based on its height, and updating it upon loading and resizing the window. The goal is to have it centered nicely next to another div (.character) positioned beside it. I ...

Attempting to organize date and time down to the second

I'm currently working on sorting time with seconds included. While I am able to sort the minutes successfully, I'm facing difficulty in sorting the seconds. Despite trying various approaches and using dynamic data that needs to be sorted in desce ...

find the repeated sequences of characters within the text

Trying to grasp a javascript string variable source; Is there an efficient technique to identify all REPEATED substrings of length around 20 characters (even if they overlap or include substrings of slightly different lengths)? An approach that could be ...

Tips for utilizing SSR data fetching in Next.js with Apollo Client

Trying to integrate the apollo-client with Next.js, I aim to fetch data within the getServerSideProps method. Let's consider having 2 components and one page- section.tsx represents component-1 const Section = () => { return ( <div& ...