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

Updating the content of a list item on the fly using React

After spending all day on this, I am feeling a bit frazzled. Trying to achieve what would take 20 seconds in JQuery has proven to be quite the challenge in React ¯\_(ツ)_/¯ In my application, tags are ranked by importance from 1 to 9. Simple enoug ...

Struggling with JavaScript's getElementById function

If anyone has any suggestions or alternative methods, please kindly assist me. I currently have: 1 Textbox 1 Label 1 LinkButton Upon clicking the lnk_NameEdit button, the txtUserName textbox should become visible while the lblusername label should becom ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

Having trouble uploading Node.js and Mongoose to Heroku due to error codes H12 and H15? Need help troubleshooting and resolving this issue?

Attempting to deploy my Node, mongoose, express app on Heroku for the first time has been a challenge. The application is a simple blog with a login system. Despite extensive research and effort, I am struggling to successfully host it. Below is the error ...

Encountering a Uncaught TypeError when attempting to split an undefined property, but issue is limited to certain pages

Recently, I've encountered an issue with iziModal on specific pages where I'm getting an error message. The error I'm facing is: Uncaught TypeError: Cannot read property 'split' of undefined at r.fn.init.t.fn.(anonymous fu ...

Dealing with error handling in NUXT using asyncData and Vue actions

The URL I am trying to access is http://mywebsite.com/[category that doesn't exist]. Despite the code snippet provided below, I am unable to reach the catch block in asyncData. async asyncData({ params, store }) { try { await store.dispatch(&ap ...

Guide to locating the recursive function in Node.js runtime

As a beginner in the world of node and angular development, I have encountered a major issue - "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory". Is there anyone who can help me identify the function ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...

Issue encountered where Moment locale functionality is working in local development environment, but not functioning properly in the

My application built with Next.js requires displaying the date in Bengali instead of English. The issue arises after running the build command 'build:next build' where the production version displays the date in English (e.g. '20 January, Su ...

Is it possible to extract information from a form's POST request without relying on the traditional "action" attribute within form elements?

Last night, I was experimenting with ExpressJS and discovered something interesting when working with a simple code snippet: app.post('/contact', function(req, res, next) { res.send('Congratulations! You have submitted the form'); }) ...

Having trouble retrieving information from the server using ajax, javascript, jquery, and php

I am currently facing an issue with sending data retrieved from a jQuery call and attempting to save it to a server file using PHP. function getSVG(){ svghead = svghead + $('#test').html(); $.ajax({ type:"POST", da ...

graphic map and paintbrush

I've implemented an image map using shape circles, but now I'm looking for a way to draw visible circles or icons on the map. Is there a solution for this issue? Currently, I have used a canvas overlay on the image to draw on it This method wo ...

Utilizing TypeDoc to Directly Reference External Library Documentation

I am working on a TypeScript project and using TypeDoc to create documentation. There is an external library in my project that already has its documentation. I want to automatically link the reader to the documentation of this external library without man ...

Attach a Material-UI Popper component to a customized edge label in a React Flow

After finding inspiration from this particular example in the react-flow documentation, I decided to create my own customized version. It showcases a Material Ui Popper that appears when the edge is selected. However, my problem arises when attempting to z ...

Creating URL query parameters for a nested REST API: A step-by-step guide

I am faced with the challenge of constructing a POST request for a nested REST API (json object) dedicated to search functionality. I am unsure about how to format the URL parameters due to its complex nesting structure. How should I include question marks ...

Issue with BCRYPTJS library: generating identical hashes for distinct passwords

After conducting a thorough search on Google, I couldn't find anyone else experiencing the same issue. The problem lies in the fact that no matter what password the user enters, the system returns the hashed value as if it is the correct password. Eve ...

Bringing in functions - NodeJS - non-HTML

Currently, I am in the process of learning automation for my job and have hit a roadblock. In times like these, stackoverflow has proven to be a life-saving resource :) My current task involves writing a Selenium test in VisualStudio using JavaScript (nod ...

Locate a specific element within an array and retrieve its corresponding index

Need help updating a boolean property for all objects in an array with the same user ID. I've outlined my MVC framework below in a concise manner. Model: var posts = [{id:1, user_id:1, is_following:true}, {id:2, user_id:1, is_cool:true}, ...

Getting Started with NPM Package Initialization in Vue

I'm attempting to incorporate the v-mask package into my Vue project using npm. Following the documentation, I executed npm install v-mask, but I am unsure where exactly to initialize the code. I tried placing it in the main.js file: import { createAp ...

The callback function for the `input` component in React Native must be a function and should not be undefined. Always remember to start component names with the proper syntax

There was a gap in my project as I have an application currently under development for testing purposes. Error: The view config getter callback for the component input must be a function (received undefined). Make sure to capitalize component names. I am ...