What is the method for dividing a string (object) to 'preserve' in a fresh piece?

Upon receiving the following JSON file:

var data = [  
   {  
      "id":"1",      
      "yMonth":"201901",
   },
   {  
      "id":"2",      
      "yMonth":"201902",
   },
   {  
      "id":"3",      
      "yMonth":"201802",
   },
   {  
      "id":"4",      
      "yMonth":"202003",
   }
]

The yMonth property in my data contains a concatenation of year and month (201901 translates to year: 2019, month: 01). I am looking to split the yMonth into two separate items for year and month, and sort them accordingly.

The desired output is as follows:

[  
    {  
      "id":"1",      
      "year":"2019",
      "month":"01",
    },
    {  
      "id":"2",      
      "year":"2019",
      "month":"02",
    },
    {  
      "id":"3",      
      "year":"2018",
      "month":"02",
    },
    {  
      "id":"4",      
      "year":"2020",
      "month":"03",
    }
]

I am considering starting with the following approach:

data.forEach(item => {
  item.yMonth..... 
   //Split string, potentially save in auxiliary variable, and create a new array with `year` and `month` items
 })

Any guidance on how to achieve this would be greatly appreciated. I am currently struggling with this task.

Answer №1

 Let newMonth = item.yMonth.slice(4);
 let newYear = item.yMonth.slice(0, 4);
 delete item.yMonth;

Answer №2

Traverse through the array using Array.map(). Within the map function, destructure and separate yMonth from each object, then extract the year and month by utilizing a Regular Expression with String.match(). Finally, merge the year and month back into the rest of the object using object spread syntax:

const data = [{"id":"1","yMonth":"201901"},{"id":"2","yMonth":"201902"},{"id":"3","yMonth":"201802"},{"id":"4","yMonth":"202003"}]

const result = data.map(({ yMonth, ...rest }) => {
  const [, year, month] = yMonth.match(/(\d{4})(\d{2})/)
  
  return {
    ...rest,
    year,
    month,
  };
})

console.log(result)

Answer №3

To extract the year and month from the given data, you can utilize the map function along with the match function within the handler.

var data = [     {        "id":"1",            "yMonth":"201901",   },   {        "id":"2",            "yMonth":"201902",   },   {        "id":"3",            "yMonth":"201802",   },   {        "id":"4",            "yMonth":"202003",   }],
    result = data.map(({yMonth, ...attr}) => {
      var [year, month] = yMonth.match(/[0-9]{2,4}/g);  
      return {...attr, year, month};
    });

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

Answer №4

This solution is perfect for my needs

const splitIndex = 2; // specify the index where to split
data.forEach(item=>{
   item.month = item.date.substring(0, splitIndex);
   item.year = item.date.substring(splitIndex);
   delete item.date;
   return item;
})

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

Can you combine multiple user validation rules with express-validator?

I have a set of rules that are almost similar, except for one where the parameter is optional and the other where it is mandatory. I need to consolidate them so that I can interchangeably use a single code for both cases. Is there a way to merge these rul ...

Updating CSS stylesheets dynamically when onchange event occurs

I am currently able to dynamically change style rules using JS, but I feel that this is limiting. I would prefer to be able to swap entire CSS stylesheet files easily. Do you have any suggestions on how to accomplish this? Here is my code: <label>T ...

Presence detected: Discord bot appears online but is missing from members list

I am embarking on the journey of creating my first Discord bot. After installing NodeJS on my computer, I used the Discord developer tools to create the app, turned it into a bot, obtained the token, selected privileges, and added the bot to my server. I ...

Quarterly Date Selection Tool with jQuery

I attempted to utilize the Quarter datepicker from: http://jsfiddle.net/4mwk0d5L/1/ Every time I execute the code, I encounter this problem: Cannot set property 'qtrs' of undefined. I copied exactly what was in the jsfiddle, and included the sam ...

CKeditor does not accept special characters or diacritics in keywords

Recently, I came across a helpful code snippet for CKeditor that counts and ranks the most used words in a textarea. This feature is invaluable for generating SEO-keywords suggestions while writing articles. However, there is an issue with non-English char ...

What is the best way to locate the position of a different element within ReactJS?

Within my parent element, I have two child elements. The second child has the capability to be dragged into the first child. Upon successful drag and drop into the first child, a callback function will be triggered. What is the best way for me to determi ...

Delete items within the first 10 minutes of shutting it down

Is there a way to temporarily remove a newsletter element for 10 minutes after closing it on a webpage? The idea is that once the panel is closed, it should stay hidden even if the page is refreshed within that timeframe. I was considering using local stor ...

Tips for incorporating an entire JavaScript file into a React JS project

I'm facing an issue with a .js file (JavaScript file) that lacks exports code, containing only a constructor and some prototype methods. I am trying to incorporate this file into my ReactJS App. My approach involved adding a script tag in client/inde ...

An elaborate warning mechanism in Redux-observable that does not trigger an action at the conclusion of an epic

I'm currently working on implementing a sophisticated alert system using redux and redux-observable. The requirements are: An action should request an alert: REQUEST_ALERT An action should create an alert and add an ID: SET_ALERT (handled in the ep ...

Tips and techniques for accessing a JPA-persisted String[] column using ResultSet#getString() in JDBC

I am exploring a method to store multiple checkbox values in a single database column. Instead of creating a separate table with @OneToMany, I want to achieve this within the same entity. Here is how the JPA entity looks: @Entity @Table(name="COOK") ... ...

Difficulty encountered when transferring an array from Xcode to JavaScript via SBJSON

In an attempt to transfer an array from Xcode to a local HTML file, I am utilizing jQuery in the HTML code. This involves using loadHTMLString: with baseURL to read both the HTML and included .js files. However, I am encountering an issue when trying to us ...

What is the best way to choose a file in an input field of type file when writing selenium test cases

When using selenium test cases, I encountered the need to select a file from an input type="file". To achieve this, I utilized the following method. browser.element(By.id('fileupload')).click(); By executing this line of code, a popup window wa ...

Updating state atoms in Recoil.js externally from components: A comprehensive guide for React users

Being new to Recoil.js, I have set up an atom and selector for the signed-in user in my app: const signedInUserAtom = atom<SignedInUser | null>({ key: 'signedInUserAtom', default: null }) export const signedInUserSelector = selecto ...

What is the best approach to make changes to a 2D array within a React component?

I'm working on saving a list of equipment in arrays, and I need to assign a quantity to each piece of equipment. To do this, I want to transform my one-dimensional array into a two-dimensional array. How can I declare a 2D array in the state? this.s ...

Arranging items into an array?

I have a query. Let me start by posting the HTML code, even though I know using tables for design is not recommended. However, in this case, it's only for educational purposes. <table id="placeholder"> <tr> <td><img src="img/ ...

Version 2 of the Microsoft Logo Animation

I made some changes to my Microsoft logo animation project. You can view the updated version on CodePen. Overall, I'm pretty happy with how it turned out except for one issue. I'm struggling to determine the right timing to end the animation so ...

Issue: Unspecified error when trying to access object attribute in Vue (Nuxt)

I am facing an issue with my 'region' object. It appears to be displayed correctly with all its attributes, but when I try to access specific attributes, it shows up as 'undefined'. const region = { "id": 7, "name": ...

Obtaining an array element from mongoose at the corresponding index of the query

My Schema looks like this: const PublicationSchema = mongoose.Schema({ title: { type: String, required: true }, files:[{ contentType: String, data: Buffer, name: String }] }) I am attempting to re ...

Run a Python function in Django without any feedback

Currently, I am utilizing Django for a project and I find myself in a situation where I need to carry out certain functions based on user input. If the action requires displaying new values, I know how to handle that. However, when I simply need to execute ...

Sending Java Servlet JSON Array to HTML

I am currently engaged in a project that requires extracting data from a MySQL database and implementing pagination. My approach involves utilizing JSON AJAX and JavaScript, although I am fairly new to JSON and AJAX. After successfully retrieving the neces ...