Guide to implementing if statements within a map function in JavaScript/Vue.js

Currently, I am developing a small application using Vuejs. In this application, I receive response data and then map it to a variable. However, there are some elements with empty arrays in the data. So, during mapping, I need to check a condition and map accordingly. Below is a snippet of my code:

this.model = a.map(i => Object.assign({
        'id': i.id,
        'meeting_date': i.schedule,
        'meeting_call': i.type,
        'event_type': i.event_type,
        'venue': i.venue,
        'with_client': i.with_client
    },{
        if(i.meeting.meeting_summaries)
        {
            'meeting_summaries': i.meeting_summaries.map(ms => ({
                client_name: ms.client_name,
                nature: ms.nature,
                action: ms.action,
                mention: ms.user_id,
                feedback: ms.feedback
            }))
        }
    },
    

Answer №1

map function in JavaScript is purely functional, meaning it does not modify the elements of an array but instead returns a newly formed array. You can utilize it like so:

this.model = a.map(i => {
  var item = {}
  item['id']= i.id,
  item['meeting_date']= i.schedule,
  item['meeting_call']= i.type,
  item['event_type']= i.event_type,
  item['venue']= i.venue,
  item['with_client']= i.with_client
  if(i.meeting && i.meeting.meeting_summaries) {
     item['meeting_summaries']= i.meeting.meeting_summaries.map(ms =>({
            client_name: ms.client_name,
            nature: ms.nature,
            action: ms.action,
            mention: ms.user_id,
            feedback: ms.feedback
        }))
  }else {
   item['meeting_summaries'] = []
  }
 return item
}

Answer №2

If you find yourself in a similar situation, consider switching to using a ternary expression:

this.model = a.map(i => Object.assign({
    'id': i.id,
    'meeting_date': i.schedule,
    'meeting_call': i.type,
    'event_type': i.event_type,
    'venue': i.venue,
    'with_client': i.with_client
}, (i.meeting.meeting_summaries) ? { // apply this if condition is met
    'meeting_summaries': i.meeting_summaries.map(ms => ({
        client_name: ms.client_name,
        nature: ms.nature,
        action: ms.action,
        mention: ms.user_id,
        feedback: ms.feedback
    }))
} : {} // otherwise, do nothing

This approach can be illustrated with the following example:

const a = [1, 2, 3, 4, 5];

const b = a.map(number => Object.assign({a: number}, 
  (number > 2) ? {b: ++number} : {}, // adds 'b' for numbers greater than 2
  (number % 2 === 0) ? {c: number + ' is even'} : {} // adds 'c' for even numbers
  ))
  
console.log(b)

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

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...

What impact does reselect have on the visual presentation of components?

I'm struggling to grasp how reselect can decrease a component's rendering. Let me illustrate an example without reselect: const getListOfSomething = (state) => ( state.first.list[state.second.activeRecord] ); const mapStateToProps = (state ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

How come jQuery is retaining the original DOM element classes even after I have modified them using jQuery?

Here is the code snippet I am working on: $(".drop-down-arrow-open i").click(function(){ console.log("The click function for .drop-down-arrow-open is triggered even when it is closed"); let thisParent = $(this).closest(".projects-container").find(".need ...

Issue with sync-request when using post data doesn't seem to be functioning

I am currently working on a Node.js application where I need to make synchronous requests. After some research, I came across the sync-request npm package for making these requests. However, when I tried using the code below, I encountered an error with th ...

Transform a JSON array with keys and values into a structured tabular format in JSON

Looking to transform the JSON data below for a Chart into a format suitable for an HTML table: var chartJson = [ { header : '2016', values : [1, 5, 9] }, { header : '2017', values : [2, 4, 8] ...

V3: Ensuring Autocomplete Stays Focused and Clears Input on Keydown Enter

Is there a way to clear the v-autocomplete without exiting the autocomplete after the user presses enter? I came across a somewhat working solution for vuefiy 3 in an answer to a similar question on Stack Overflow. While it didn't completely solve my ...

Issues with executing google.script.run in Google Web App

I am encountering an issue with the function I have defined in my .gs file: function doGet(e) { return HtmlService.createHtmlOutputFromFile('index') } function goToMaster() { const ss = SpreadsheetApp.getActiveSpreadsheet() const sheet = s ...

Mastering VSCode IntelliSense: Unleashing the Power of Type Declarations

In my JavaScript projects, I aim to include TypeScript types sparingly to leverage IntelliSense for better code completions and receive warnings about type-related issues. To set up typechecking in JS, I created a jsconfig.json file and rely mostly on JSD ...

Tips to instantiate an object of a different JavaScript class in Node.js

Hey there! I'm having trouble creating an instance of ProfileComparator in a different JavaScript file called index.js. Can someone help me resolve this error? strategy.js var cosineUtils = require("./jscosine"); var ProfileComparator = function(al ...

Create data according to jQuery's AJAX data method

When editing in place using jQuery, if the code snippet seems too complicated, please refer to a simpler one. 'column2' => "RAJANgsfdgf" 'column3' => "SRARDHAMgsdfgdf" 'column4' => "40043433" 'column7' =&g ...

What prevents me from calling a function while it is being defined in the prototype?

I am experimenting with inheritance through an example. I want to access all properties of objects abc and pqr, so I decided to use Object.create. However, when I try to get the value of r by calling the getr() function, it doesn't seem to work as exp ...

Manipulate jQuery to set the table row containing empty table data cells to be lower than the row with

I am using HTML and jQuery to sort my table, including non-standard sorting with multi-tbody. The issue I am facing is that the prices (Цена) in the td are sorted ascending but not correctly. Why is this happening? Additionally, I need to move the tr&a ...

Exploring the Haversine Formula and Geolocation Integration in AngularJS

I am currently developing an application that will organize locations based on either name or distance from the user. Everything is functioning properly except for retrieving the distance. I believe I should be able to obtain the user's coordinates th ...

Vue main component fails to detect emitted events from child component

I am working on a website that will showcase multiple cards which expand when selected. Here is the code for the card component: <template> <v-card class="mx-auto" max-width="90%" min-height="6 ...

What steps do I need to take in order to generate a legitimate link annotation within Adobe Acrobat by utilizing Acrobat

Seeking guidance on how to embed an Acrobat Javascript within Adobe Acrobat in order to generate a link annotation. The current method involves using the "addLink" function within the document object, which triggers a Javascript action upon clicking the li ...

Tips for dynamically assigning unique IDs to HTML form elements created within a JavaScript loop

let count = 0; while (count < 4) { $('#container').append("<div><input type='textbox' class ='left' id='left-${count}'/><input type='textbox' class ='right' id=' ...

Is there a way to establish a condition for an onSubmit event?

I have a form that I'm working on, and I would like for an error message to pop up upon the first onSubmit, and then function normally on subsequent submissions. Here is the current setup: const [submitting, setSubmitting] = useState(false); const ha ...

Discover the power of utilizing the reduce function to extract the value of a specific field within an array of Objects

In the following example, we have an object with 3 forms: formA, formB, and formC. Form A and B are objects, while formC is an array of objects that can contain multiple items. const object: { "formA": { "details": {}, ...

Information is not appearing in the dropdown menu

As a beginner in JavaScript, this is my first program. I have written HTML and JavaScript code to display data in a dropdown menu from a Python Django database. However, when I run it, the data is not showing up. Here is my code: <!DOCTYPE html> < ...