Guide to generating a fresh array by using a third array as a reference point?

My array called structuredFormData contains the following information:

[
  {
    "season": "autumn",
    "firstContactPersonName": "John",
    "firstContactPersonPhone": "46442644",
    "secondContactPersonName": "Jhonny",
    "secondContactPersonPhone": "46442644"
  },
  {
    "season": "christmas",
    "firstContactPersonName": "Tommy",
    "firstContactPersonPhone": "46442644",
    "secondContactPersonPhone": "Thomas"
  }
]

In addition, I have an array named selectedDate, which holds the dates:

["autumn=2020-08-28", "christmas=2020-12-28"]

To update my data for backend communication, I am using a function that creates or updates another array named updatedStructuredFormData. This function maps through the structuredFormData and assigns relevant dates from the selectedDate array.

let updatedStructuredFormData = structuredFormData.map(x => {
            let season = x.season;
            x.date = selectedDate.find(e => e.indexOf(season) > -1).split("=")[1];
            return x;
        });

The challenge arises when only one date is selected and the selectedDate array looks like this: ["autumn=2020-08-28"]. In such cases, I need to filter the values accordingly.

{
"season": "autumn",
"firstContactPersonName": "John",
"firstContactPersonPhone": "46442644",
"secondContactPersonName": "Jhonny",
"secondContactPersonPhone": "46442644"
}

Currently, I'm struggling with filtering out only the selected values in the dates array. Any assistance or guidance on how to achieve this would be greatly appreciated.

The desired outcome should look like:

[
    {
      "season": "autumn",
      "firstContactPersonName": "John",
      "firstContactPersonPhone": "46442644",
      "secondContactPersonName": "Jhonny",
      "secondContactPersonPhone": "46442644",
      "date": "2020-08-28"
    }
]

If the selectedDate array also includes a date for Christmas as well

["autumn=28-08-28", "christmas=2020-12-28"]
, then the expected result would incorporate both dates:

[
    {
      "season": "autumn",
      "firstContactPersonName": "John",
      "firstContactPersonPhone": "46442644",
      "secondContactPersonName": "Jhonny",
      "secondContactPersonPhone": "46442644",
      "date": "2020-08-28"
    },
    {
      "season": "christmas",
      "firstContactPersonName": "Tommy",
      "firstContactPersonPhone": "46442644",
      "date": "2020-12-28"
     }
]

Thank you for your help :)

Answer №1

Here is a method to achieve this using .reduce():

// Array to filter
const arr = [
  {
    season: "summer",
    firstContactPersonName: "Sarah",
    firstContactPersonPhone: "123456789",
    secondContactPersonName: "Samantha",
    secondContactPersonPhone: "987654321"
  },
  {
    season: "winter",
    firstContactPersonName: "Michael",
    firstContactPersonPhone: "555666777",
    secondContactPersonPhone: "Michelle"
  }
];

// Dates to filter for
const selectedDates = ["summer=05-25-21", "winter=2021-01-15"];

// Iterate over each item and filter for the specified season in "selectedDate"
const filteredItems = arr.reduce((accumulator, current) => {
  const maybeDate = selectedDates.filter(date => date.includes(current.season));

  if (maybeDate.length > 0) {
    const dateValue = maybeDate[0].split("=")[1];
    accumulator = [...accumulator, { ...current, date: dateValue }];
  }

  return accumulator;
}, []);

console.log({ filteredItems });

// Output
{
  filteredItems:
  [{
    season: 'summer',
    firstContactPersonName: 'Sarah',
    firstContactPersonPhone: '123456789',
    secondContactPersonName: 'Samantha',
    secondContactPersonPhone: '987654321',
    date: '05-25-21'
  },
  {
    season: 'winter',
    firstContactPersonName: 'Michael',
    firstContactPersonPhone: '555666777',
    secondContactPersonPhone: 'Michelle',
    date: '2021-01-15'
  }]
}

Answer №2

To solve this problem, follow these steps:

  1. First, convert selectedDate into an array containing objects with season and date properties:

     const seasonDates = dates.map(d => ({
      season: d.split('=')[0],
      date:d.split('=')[1]
     }))
    
  2. Next, calculate transformedStructuredFormData with dates:

    const transformedStructuredFormData = structuredFormData.map(d => {
      const time = seasonDate.filter(i => i.season === d.season)
    
      if (time.length) d.date = time[0].date;
    
      return d;
    })
    


    Putting it all together:

const structuredFormData = [{
    "season": "autumn",
    "firstContactPersonName": "John",
    "firstContactPersonPhone": "46442644",
    "secondContactPersonName": "Jhonny",
    "secondContactPersonPhone": "46442644",
  },
  {
    "season": "christmas",
    "firstContactPersonName": "Tommy",
    "firstContactPersonPhone": "46442644",
    "secondContactPersonPhone": "Thomas",
  },
];

const selectedDate = ["autumn=2020-08-28", "christmas=2020-12-28"];

const seasonDates = selectedDate.map(d => ({
  season: d.split('=')[0],
  date: d.split('=')[1]
}));

const transformedFormData = structuredFormData.map(d => {
  const time = seasonDates.filter(i => i.season === d.season);
  
  if (time.length) d.date = time[0].date;

  return d;
});

console.log(transformedFormData)

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

Transfer the index of a for loop to another function

Can you explain how to pass the 'i' value of a for loop to a different function? I want to create a click function that changes the left position of a <ul> element. Each click should use values stored in an array based on their index posi ...

Can image data be extracted from a canvas without needing to physically render the canvas?

I am currently working on an Angular application that utilizes Chart.js to create dynamic charts in various views. Additionally, the application has the capability to export data to a PDF format using the PDFMake JavaScript library, which is a basic tool a ...

Show search results in real-time as you type

I am currently developing a SharePoint 2007 web part using Visual Studio. The main goal of this web part is to search a SharePoint list and present the results to the user. My objective is to have the results displayed automatically once the user finishes ...

What is the method or variable called "afterShow" used for in FancyBox V4 and how does it differ from its counterpart in JQuery-FancyBox V3?

We previously utilized the V3 edition of Fancybox, incorporating our increaseImageClicks and increaseVideoClicks functions within its afterShow function: /* FANCYBOX OLD (https://web.archive.org/web/20210325170940/https://fancyapps.com/fancybox/3/docs/): * ...

Streamline the organization of parent roles

var classFinder = $('.frame').parent().parent().parent().parent().parent(); if (classFinder.hasClass(".class")) { return true; } I have identified a class along this specific path^... Is there a way to streamline this process ...

Halt! There is a Syntax Error: anticipating an expression, but instead received the keyword 'for'

I'm encountering an issue with this code. I need help to figure out how to print a loop inside dynamiHTML. Can anyone assist me? function createDiv(data){ var dynamicHTML = ''; alert(data.res2.length); dynamicHTML += '<div ...

Unable to forward page in EJS

Hey everyone, I've been struggling with trying to redirect to a page in EJS, but it just doesn't seem to work for some reason. Here's my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...

Check if there are any child nodes before executing the RemoveChild JavaScript function to avoid any errors

function delete(){ let k = document.getElementsByClassName('row'); for(let i=0; i<k.length; i++) { if(k[i].hasChildNodes()){ k[i].removeChild(k[i].childNodes[2]); } } } <div id="table"> <div class="row"& ...

Using JavaScript to create a dynamic to-do list that persists on the browser even when refreshed

I created a Javascript Todolist that is functioning well, but I am seeking a way to ensure that my Todo-items persist on the browser even after refreshing until I choose to delete them. Any suggestions or advice on how I can achieve this? ...

Navigate to the location using AngularJS elements in the JavaScript iframe1

Dealing with an issue while working on AngularJS. I am facing a frustrating problem where I am attempting to use one link to open links in two separate iframes. All aspects of this function correctly, except for the actual links. The issue arises when usin ...

The feature of using a custom find command in Cypress does not support chaining

I am interested in developing a customized Cypress find command that can make use of a data-test attribute. cypress/support/index.ts declare global { namespace Cypress { interface Chainable { /** * Creating a custom command to locate a ...

Sorry, but React does not accept objects as valid children. Make sure the content you are passing is a valid React child element

I encountered an issue with rendering on a screen that involves receiving an object. The error message I received is as follows: Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection o ...

Encountering a "403 Forbidden" error upon deployment to the server due to

Situation: I am developing a website using Spring web MVC, JSP, and HTML/JavaScript. One of the features I have implemented is a search function that communicates with imdbapi.org to retrieve movie/TV show information in JSON format via AJAX. The JSON resp ...

Switching Symbols with JQuery

Hello, I am brand new to utilizing javascript and I'm currently experimenting with the toggle function. My goal is to create show/hide functionality while also toggling arrow icons. Specifically, I want a right arrow next to the link "More -->" and ...

Modifying Selectize Ajax data in real-time

How can the student_id be changed each time the modal is opened? This is the code: $('#relationshipModal input[name=existing_user]').selectize({ valueField: 'id', searchField: 'name', options: [], create: fal ...

What is the most efficient way to retrieve the key at a specific index within a JavaScript map object?

If I have the map object shown below: const items = new Map([['item1','A'], ['item2','B'], ['item3', 'C']]) I am trying to retrieve the key at index 2. Is there a method other than using a for ...

Sending cookies via POST/GET request with Credentials is not functioning

Greetings, despite the numerous duplicates of this inquiry, my attempt to solve it has been unsuccessful. Therefore, I am initiating a fresh discussion. Aside from utilizing axios, I also experimented with fetch but encountered similar outcomes. On the b ...

Is there a way to programmatically toggle a button's enabled state depending on the content of a text input field?

I want to create a functionality where a button will be enabled if the value in a textbox is 'mypassword'. If it's not equal to 'mypassword', then the button should be disabled. I've attempted the code below, but it doesn&apos ...

Retrieve the value of the second child element in a table cell when clicking on it with Javascript

I have created a table with one row that includes the title of the month and a cell containing an inner table with multiple rows and cells. I want to display the content of the second cell in the second table as a modal box or alert dialog when it is click ...

The onPlayerReady function in the YouTube API seems to be experiencing a delay and

After following a tutorial on integrating the YouTube API into my website, I encountered difficulties trying to play a YouTube video in fullscreen mode when a button is pressed. Despite following the provided code closely, I am unable to get it to work as ...