Updating elements within a subarray in JavaScript can easily be accomplished by accessing the

I need help updating nested array elements in JavaScript. I want to convert dates into a different format. How can I update the nested elements?

array1 = [
{
"week": [
"2019-05-06T16:00:00.000Z",
"2019-05-07T16:00:00.000Z",
"2019-05-08T16:00:00.000Z",
"2019-05-09T16:00:00.000Z",
"2019-05-10T16:00:00.000Z",
"2019-05-11T16:00:00.000Z",
"2019-05-12T16:00:00.000Z"
],
"weekNumber": 19
},
{
"week": [
"2019-05-20T16:00:00.000Z",
"2019-05-21T16:00:00.000Z",
"2019-05-22T16:00:00.000Z",
"2019-05-23T16:00:00.000Z",
"2019-05-24T16:00:00.000Z",
"2019-05-25T16:00:00.000Z",
"2019-05-26T16:00:00.000Z"
],
"weekNumber": 21
},
{
"week": [
"2019-06-03T16:00:00.000Z",
"2019-06-04T16:00:00.000Z",
"2019-06-05T16:00:00.000Z",
"2019-06-06T16:00:00.000Z",
"2019-06-07T16:00:00.000Z",
"2019-06-08T16:00:00.000Z",
"2019-06-09T16:00:00.000Z"
],
"weekNumber": 23
}
];

expectedResult = [
{
"week": [
"2019-05-06",
"2019-05-07",
"2019-05-08",
"2019-05-09",
"2019-05-10",
"2019-05-11",
"2019-05-12"
],
"weekNumber": 19
},
{
"week": [
"2019-05-20",
"2019-05-21",
"2019-05-22",
"2019-05-23",
"2019-05-24",
"2019-05-25",
"2019-05-26"
],
"weekNumber": 21
},
{
"week": [
"2019-06-03",
"2019-06-04",
"2019-06-05",
"2019-06-06",
"2019-06-07",
"2019-06-08",
"2019-06-09"
],
"weekNumber": 23
}
];

I want to remove ":00:00.000Z". I have a formatting function that removes that but I am unsure how to call it here.

Answer №1

You should utilize the functions map and split

let list = [{"week": ["2019-05-06T16:00:00.000Z","2019-05-07T16:00:00.000Z","2019-05-08T16:00:00.000Z","2019-05-09T16:00:00.000Z","2019-05-10T16:00:00.000Z","2019-05-11T16:00:00.000Z","2019-05-12T16:00:00.000Z"],"weekNumber": 19},
{"week": ["2019-05-20T16:00:00.000Z","2019-05-21T16:00:00.000Z","2019-05-22T16:00:00.000Z","2019-05-23T16:00:00.000Z","2019-05-24T16:00:00.000Z","2019-05-25T16:00:00.000Z","2019-05-26T16:00:00.000Z"],"weekNumber": 21},
{"week": ["2019-06-03T16:00:00.000Z","2019-06-04T16:00:00.000Z","2019-06-05T16:00:00.000Z","2019-06-06T16:00:00.000Z","2019-06-07T16:00:00.000Z","2019-06-08T16:00:00.000Z","2019-06-09T16:00:00.000Z"],"weekNumber": 23}];

let result = list.map(item=>{
  item.week = item.week.map(value => value.split('T',1)[0])
  return item
})

console.log(result)

Answer №2

If you wish to create a new array, you can utilize the map function or embed one map within a forEach. This essentially requires nested mapping.

The following illustration demonstrates the use of two nested map functions. Within the inner map, each element in the week is iterated upon utilizing the Date object. If there exists a separate function, it can be invoked within the callback function of the inner map as shown below:

 let newfmt = array1.map(function(item) {
      return {
        week: item.week.map(function(elem) {
          // 'elem' here represents each value within the week array.
          // Since map generates an array, 'week' will be an array consisting of formatted dates
          return yourFunction(elem)
        }),
        weekNumber: item.weekNumber
      }
    })

let array1 = [{
    "week": [
      "2019-05-06T16:00:00.000Z",
      "2019-05-07T16:00:00.000Z",
      "2019-05-08T16:00:00.000Z",
      "2019-05-09T16:00:00.000Z",
      "2019-05-10T16:00:00.000Z",
      "2019-05-11T16:00:00.000Z",
      "2019-05-12T16:00:00.000Z"
    ],
    "weekNumber": 19
  },
  {
    "week": [
      "2019-05-20T16:00:00.000Z",
      "2019-05-21T16:00:00.000Z",
      "2019-05-22T16:00:00.000Z",
      "2019-05-23T16:00:00.000Z",
      "2019-05-24T16:00:00.000Z",
      "2019-05-25T16:00:00.000Z",
      "2019-05-26T16:00:00.000Z"
    ],
    "weekNumber": 21
  },
  {
    "week": [
      "2019-06-03T16:00:00.000Z",
      "2019-06-04T16:00:00.000Z",
      "2019-06-05T16:00:00.000Z",
      "2019-06-06T16:00:00.000Z",
      "2019-06-07T16:00:00.000Z",
      "2019-06-08T16:00:00.000Z",
      "2019-06-09T16:00:00.000Z"
    ],
    "weekNumber": 23
  }
];

let newfmt = array1.map(function(item) {
  return {
    week: item.week.map(function(elem) {
      let dt = new Date(elem);
      return `${dt.getFullYear()}-${dt.getMonth()}-${dt.getDay()}`
    }),
    weekNumber: item.weekNumber
  }
})
   console.log(newfmt)

Answer №3

One way to approach this is by using Object.assign like so:-

const original = { name: "John", age: 30 }
const updated = Object.assign({}, original, { name: "Dave" });
console.log(updated);

Instead of just updating the name, you can loop through each day of the week and apply different formatting.

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

Is there a way to show additional information beyond just the title in FullCalendar?

Hello, I am currently using the full calendar plugin and have a question. While I can display the title of events on my calendar, I would also like to display additional information from my database (such as full name or description) alongside the title. H ...

Node.JS program unexpectedly logging MySQL results to console and exhibiting erratic behavior

Recently, I encountered a peculiar error while working with Node.JS MySQL. Strangely, I noticed that a result was being logged in the console without any corresponding code line instructing it to do so. Even more baffling was the fact that when I intention ...

Modifying app aesthetics on-the-fly in Angular

I am currently working on implementing various color schemes to customize our app, and I want Angular to dynamically apply one based on user preferences. In our scenario, the UI will be accessed by multiple clients, each with their own preferred color sch ...

JQGrid will automatically conceal any row that contains a false value in a given cell

I'm attempting to conceal a row if a specific cell within it contains the value false. To achieve this, I have experimented with using a formatter in the following manner: $("#list").jqGrid({ //datatype: 'clientSide', ...

Is it possible for the outcome of a component to be passed to render and actually show up as undefined

I am currently working on creating a wrapper component for an API call in order to display "loading" if the API hasn't updated yet. As I am new to React, I am struggling with passing the state to the ApiResp component: After checking the console.log ...

Positioning the comments box on Facebook platform allows users to

Need assistance, I recently integrated the Facebook comments box into my Arabic website, but I am facing an issue where the position of the box keeps moving to the left. Here is an example of my website: Could someone please suggest a solution to fix the ...

Enhancing the Calculator Functionality in a React Program

I'm struggling to incorporate a reset button into the input field, similar to CE on a calculator. I'm facing challenges when it comes to integrating it within the existing code structure. import { useRef } from "react"; import './A ...

using the information from the child array within a v-if condition

I'm struggling to extract data from a child array and utilize it in my v-if condition. Below are my data and code. Any assistance would be appreciated, even if it's just pointers to the right documentation. <div class='post' v-for= ...

forEach`` binding in knockout object

data:[ "properties": {"CountryName": "qwerty", "Population":"785004"} ] features:[ "properties": {"LastName": "abc"} ] .... Retrieving information from a JavaScript object called data and storing it in another. resultData = ...

Is it possible to conceal the contents of a details tag without using a summary tag?

I'm looking for a way to hide the details tag without the summary. In my code, the summary is only visible when a condition [isvisible == false] is met. However, even when the summary is not visible, the details keyword is still shown and I want to hi ...

What is the functionality of the remote data source in Jquery Mobile autocomplete feature?

Currently, I am browsing through this page and it appears that there is no clear documentation provided on the expected format or functionality of the remote data source. The example JavaScript code on the website references a remote data source at http:/ ...

Two separate projects targeting Admin and User interfaces versus a unified application featuring distinct themes for each user role

In React, there is a scenario that needs to be implemented. An admin panel with various functionalities like Auth, charts, analytics, and user management has already been pre-built. The goal now is to connect this admin panel to another website as the back ...

Removing solely the selected item, leaving the rest of the elements on the canvas untouched

Just starting out with coding and working on a game for a school project. The idea is to have random circles or "targets" appear on the screen, and the user has to click them. I've been struggling with keeping the "un-clicked" circles on the canvas wh ...

Turning a JSON string into interpolation within an Angular application

I received a JSON response that looks like this: { someText: "Order in {000} 12pm PST for early shipping"; cutofftime : "10000000" } What is the most effective way to replace the '{000}' with the dynamic value stored in &quo ...

Sharing data from JavaScript to view in Rails: A step-by-step guide

After clicking the submit button, the controller renders with JSON data. The JSON data is {notes: array[1], array[2]}. The next step is to render the view.html.erb file. How can the values in notes be displayed like <%= notes %> in this file? ...

Is there a way to prevent jQuery.ajax() from displaying errors in the console?

I have set up a jQuery JSONP request to monitor the status of a resource based on its URL. In case the resource is not accessible or the server goes down, my ajaxFail() function takes care of updating the display. function fetchServerStatus(service, host) ...

Having trouble displaying values from nested JSON in a datatable

Response from server : ["{\"CLIENT\":[{\"tranche\":\"1-4\",\"prix\":\"65.96\",\"currency\":\"E\"}],\"DISTRIBUTEUR\":[{\"tranche\":\"1-4\",\"prix\ ...

Tips for displaying a resolved promise in React js after using the `then` method

While working with promises, I encountered this error: Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous task ...

How can you preselect an item in Vuetify's item group?

When attempting to preselect an item from a vuetify item-group, I discovered that it works with strings but not with objects. The vuetify documentation shows using a string array as the item list for the item-group, which functions correctly. However, whe ...

Nativescript encountered an issue while attempting to generate the application. The module failed to load: app/main.js

I'm currently experimenting with the sample-Groceries application, and after installing NativeScript and angular 2 on two different machines, I encountered the same error message when trying to execute: tns run android --emulator While IOS operations ...