What is the best way to transform an array of string values into an array of objects?

I currently have an array of strings with date and price information:

    const array = [
       "date: 1679534340367, price: 27348.6178237571831766",
       "date: 1679534340367, price: 27348.6178237571831766",
       "date: 1679534340367, price: 27348.6178237571831766",
       "date: 1679534340367, price: 27348.6178237571831766",
       "date: 1679534340367, price: 27348.6178237571831766"
    ]

My goal is to transform this array into a new array of objects structured like this:

   const array = [
      {"date": 1679534340367, "price": 27348.6178237571831766},
      {"date": 1679534340367, "price": 27348.6178237571831766},
      {"date": 1679534340367, "price": 27348.6178237571831766},
      {"date": 1679534340367, "price": 27348.6178237571831766},
      {"date": 1679534340367, "price": 27348.6178237571831766},
   ]

Answer №1

To escape object keys, you can utilize the .replace function with regular expressions. Next, encase the keys in curly braces by wrapping the string with {}, and finally convert it to an object using JSON.parse()

array.map((i) => {
    let item = i;

    // escape "date" key
    item = item.replace(/date:/, '"date":');

    // escape "price" key
    item = item.replace(/price:/, '"price":');

    // wrap string with curly braces
    item = `{${item}}`;

    // call JSON.parse func
    return JSON.parse(item );
})

Alternatively, you can achieve the same result without intermediate steps:

array.map((item) =>
  JSON.parse(
    `{${item.replace(/date:/, '"date":').replace(/price:/, '"price":'}}`,
  ),
);

Answer №2

One effective approach, in my humble opinion, is utilizing regular expressions:

const array = [
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766"
];

const newArray = array.map(str => {
  const matches = str.match(/date: ([\d.]+), price: ([\d.]+)/);
  return { date: Number(matches[1]), price: Number(matches[2]) };
});

console.log(newArray);

Furthermore, another viable option would be to employ a map and split strategy:

const array = [
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766"
];

const newArray = array.map(str => {
  const parts = str.split(", ");
  const date = parts[0].split(": ")[1];
  const price = parts[1].split(": ")[1];
  return { date: Number(date), price: Number(price) };
});

console.log(newArray);

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

AngularJS ng-onclick method sending value to Thymeleaf

I am facing an issue with the integration of Thymeleaf and AngularJS. Below is the Thymleaf page I have: <div ng-controller="ctrlsubcomment" > <div class="media" th:fragment="comments" th:each="newsComment : ${comments}"> <img ...

Once invoked by an ajax request, the $().ready function is executed

The functionality of this code is flawless when running on its own. However, once I make an ajax call to it, the code fails to execute. I suspect that the issue lies within $().ready, but I haven't yet identified a suitable replacement. Any suggestio ...

Upon being provided with a route param, the response will be

For my current project using Express, I want to implement Reddit-like functionality where appending ".json" to any URL will return JSON data instead of the rendered template. To set up the rendering engine in Express, I am using Jade. Here is how I config ...

Error in Leaflet: Uncaught TypeError: layer.addEventParent is not a function in the promise

Having trouble with Leaflet clusterGroup, encountering the following error: Leaflet error Uncaught (in promise) TypeError: layer.addEventParent is not a function const markerClusters = new MarkerClusterGroup(); const clusters = []; const markers = []; co ...

Looking for a way to add interactivity to this canvas rectangle?

ctx.fillStyle = "#9b958c"; ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH); ctx.fillStyle = "#fff"; ctx.fillText("Click here to play again.", sampleTextX, sampleTextY); This clickable rectangle has been giving me some trouble. While I fou ...

Developing and integrating views within a node-webkit desktop application

For my file copier desktop application built with node webkit, I aim to create a seamless flow where the initial check for existing profile data determines the first page displayed. The header with static links/buttons to various views remains consistent ...

Developing a Cloud Function for Stripe that is taking forever to finalize writing data to Firestore

Currently, I am facing an issue with my Google Cloud function (provided below) that handles webhooks from Stripe payments and stores some data in Firestore. The problem is that it seems to hang for approximately 3 minutes before completing. const Stripe = ...

Expanding div width with jQuery as a percentage

Currently, I am facing a dilemma as I try to devise an equation for expanding the width of a div based on its current height. The Scenario Within this situation, there is a div that features a background image set to "contain." The original background ima ...

Graph is not showing up when navigating through page

On my List page (List.Html), users can select multiple rows to display the data in a chart using C3. However, when clicking on the compareList() button to navigate to the Chart page (Chart.Html), the chart does not display properly. It seems that the chart ...

Show or hide a fixed position div using jQuery when clicked

I am new to jQuery and I am trying to create a "full page menu" on my own. However, I am struggling to hide the menu on the second click. I tried using .toggle() but I found out that it has been deprecated. Can someone assist me with this? Thank you so muc ...

Receiving time slots on a bootstrap schedule

I recently developed a calendar using Bootstrap that allows users to select a start date and automatically sets the end date within a 7-day range from the chosen start date. However, I am facing a challenge in enabling users to also pick minutes along with ...

Using ng-bind-html within a ng-repeat loop

Currently, I am working on developing a custom autosuggest feature where a web service is queried with a search term to retrieve a list of suggestions that are then displayed. My main obstacle lies in trying to highlight the matching term within the sugges ...

Is there a way to transpile a dependency within the node_modules directory when using Nuxt 2?

I have come across challenges when transpiling node_modules with Nuxt, but the latest version of Nuxt (2.0) seems to have addressed this issue by introducing a transpile option in the nuxt.config.js file. https://nuxtjs.org/api/configuration-build/#transp ...

Changing the CSS class of the Bootstrap datetime picker when selecting the year

Is there a way to change the CSS style of the Bootstrap datetime picker control so that when selecting years, the color changes from blue to red? I attempted to do this with the following code: .selectYear { background-color:red!important; } However ...

Encountering a problem involving the apostrophe character "'" when trying to save content into a MySQL database

I have been developing an application that allows users to create HTML templates and save them. Users can utilize different components such as text, images, etc. to build HTML pages. Challenge: The issue I'm encountering is when a user inputs text wi ...

What is the proper sequence for binding jQuery to elements?

I'm currently facing a challenge with using jQuery to link a function to an element. Essentially, I'm loading a series of divs via JSON, with each item in the JSON having an "action" assigned to it that determines which function should be trigger ...

Achieving Optimal Performance with Node.js Cluster in High-Traffic Production Settings

Currently, my web service is managing http requests to redirect users to specific URLs. The CPU is currently handling around 5 million hits per day, but I am looking to scale it up to handle over 20 million. However, I am hesitant about using the new Nod ...

Having trouble identifying the issue with the dependent select drop down in my Active Admin setup (Rails 3.2, Active Admin 1.0)

I am currently working on developing a Ruby on Rails application that involves three models: Games that can be categorized into a Sector (referred to as GameSector) and a subsector (known as GameSubsector) A sector consists of multiple subsectors. A Subs ...

Prevent users from tabbing to the next input field in a web form

Is it possible to prevent users from using the tab button on their keyboard to navigate to the next field in a form? <form action="/action_page.php"> First name:<br> <input type="text" name="firstname"> <br> Last name:< ...

What is the process for implementing THREE.EdgesGeometry on a model imported using THREE.OBJLoader?

I have been attempting multiple times to add edges in a model loader using the OBJLoader, but I am unable to achieve it. Mloader = new THREE.MTLLoader(); Mloader.setPath( dir ); Mloader.load( mtl_dir, function ( materials ) { ...