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

Using ASP.NET MVC 6 Web API along with Angular, a resource can be posted as an object property in the

I am facing a challenge in sending a complex object from Angular to my web API. Here is how the object looks: { Name: "test", Tax: 23, Addresses: [ { country: "ro", city: "bucharest" }, { country: "fr", ...

Unleashing the Power of Node.js: A Step-by-Step Guide to Crafting

I am developing a console interface that prompts the user with questions and receives input through the console. Some questions require the user to provide a limited number of inputs. I have researched ways to obtain console input in node js, but I haven&a ...

Pandas: The ultimate tool for creating custom multilevel JSON responses

Looking to transform the data output below into a pandas dataframe with specific columns: List (whitelist, blacklist) QueryWord (gun, trench concrete, tripod....) ContextWord (1, 2, 3, 4...) Score (0.1, 0.2....) api_output = {"whitelist": ...

Exploring the Power of Pengines in Combining Prolog with Javascript

I'm currently working on an artificial intelligence project that utilizes Prolog, and I'm looking to publish it online. I came across pengines (http://pengines.swi-prolog.org/docs/documentation.html, http://www.swi-prolog.org/pldoc/doc_for?object ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

What are some effective strategies for incorporating multiple Themes into an AngularJS project?

Currently, I am in the process of working on a project that involves utilizing AngularJS, UI Bootstrap, and Sass. The next step is to incorporate different themes that can be selected by the user. While I have successfully implemented the ability to apply ...

Is it important to minify JavaScript npm packages?

In my journey of creating numerous npm packages, I find myself pondering over the question: "Should JavaScript npm packages be minified?" I have always held the belief that minifying already minified code is not a good practice, which is why I have refrai ...

Is compiling inline sass possible with npm?

Looking for a simple method to achieve this task? I've experimented with sass, node-sass, and tinysass without success. My goal is to compile inline sass in JavaScript, much like the code snippet below: import sassPkg from 'sass-pkg' const ...

Ways to prompt a specific text value to generate varied responses

Whenever I try to input the letter "h", I expect a specific value in return but for some reason, it's not working as intended. Despite my best efforts to troubleshoot the issue, I have been unsuccessful in finding a solution. It's frustrating bec ...

The AngularJS directive "ng-include" is used to dynamically

I am encountering an issue with ng-include not retrieving the file. What could be the reason for the problem in accessing a property from a link within ng-include? I would appreciate any assistance with resolving this matter. (function(){ var app = angu ...

Step-by-step guide on concealing elements and subsequently displaying them upon clicking the containing DIV

It's a bit tricky to explain without visuals, so I suggest checking out the JSFiddle link provided. Essentially, when a specific div is clicked, it should expand to reveal some inputs and buttons. However, the issue I'm facing is that upon loadin ...

Interpret the JSON reply

Could someone please explain why my function B() is not responding? <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/ja ...

Calculating the time difference between two dates in the format yyyy-MM-ddTHH:mm:ss.fffffff can be done by following these steps

Can someone help me figure out how to calculate the difference in days between the date and time 2021-02-23T08:31:37.1410141 (in the format yyyy-MM-ddTHH:mm:ss.fffffff) obtained from a server as a string, and the current date-time in an Angular application ...

res.json responding with altered input unexpectedly

When I use my res.json function, it seems to be altering my data. The data appears correct when logged in the function, but changes inside res.json and I can't figure out why. For example, instead of returning {"unix":"1484600306","naturalFormat":"20 ...

What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this. // Apply code for max-width = 520px const myBtn = document.getElementById("darktheme"); const ...

Navigating Through the DOM with Selenium using XPath Axes

Currently, I am developing Selenium tests for a dynamic web page. Within this section of code, I am extracting data from an Excel sheet and verifying if a specific element exists on the webpage. I have annotated the critical part of the code with comments ...

What is the best way to incorporate a variable in the find() method to search for similar matches?

I've been working on a dictionary web application and now I'm in the process of developing a search engine. My goal is to allow users to enter part of a word and receive all similar matches. For instance, if they type "ava", they should get back ...

Angular 7 offers seamless synchronization for horizontal scrolling in a unique way

Can anyone provide guidance on how to achieve synchronized horizontal scrolling in an Angular project? I found a solution at the following link, but it uses jQuery code. Synchronized scrolling using jQuery? ...

What is the most effective way to retrieve 'this' within an object method that is being used as a callback function?

I am currently working on a word game project to enhance my understanding of JavaScript, especially since I am new to it. To facilitate user interaction, I am utilizing the NPM package prompt (https://www.npmjs.com/package/prompt). Coming from an OOP back ...

AngularJS making a HttpPost request resulting in a 500-Internal Server Error

I'm currently working on an application where I need to include a user in the database which requires a POST operation. However, every time I try to run the application, I encounter a 500-Internal Server Error for the POST API call. Here is a snippe ...