A guide to combining two properties from a single object within an object using JavaScript

let aboutMark = {
  firstName: "Mark",
  lastName: "Miller",
  height: 1.69,
  weight: 78,
  bmiCalculator: function(){
    this.markBMI = (this.weight / (this.height * this.height)) 
    return  this.markBMI
  }
};
aboutMark.bmiCalculator()
console.log(aboutMark);

I'm looking to enhance the aboutMark object by adding a new property that combines the values of firstName and lastName together. How could we achieve this?

Answer №1

You have the option to create a value after the object has been created.

aboutMark['fullName'] = aboutMark.firstName + " " + aboutMark.lastName;

Alternatively, you can create a dynamic function and then call it using

console.log(aboutMark.fullName())

let aboutMark = {
    firstName: "Mark",
    lastName: "Miller",
    height: 1.69,
    weight: 78,
    bmiCalculator: function(){
        this.markBMI = (this.weight / (this.height * this.height))
        return  this.markBMI
    },
    fullName: function(){
        return this.firstName + " " + this.lastName
    }
};

Another approach is to utilize a getter, with credit to @Nick Parsons

let aboutMark = {
    firstName: "Mark",
    lastName: "Miller",
    height: 1.69,
    weight: 78,
    bmiCalculator: function(){
        this.markBMI = (this.weight / (this.height * this.height))
        return  this.markBMI
    },
    get fullName(){
        return this.firstName + " " + this.lastName
    }
};

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

Remembering data in a lazy loaded AngularJs list

Encountering an issue with a lazy loaded list of books. Initially, 10 books are loaded and if the user scrolls down, the next 10 books are loaded. For example, if the user is on "page" 4 and clicks on the 35th book to view details, upon returning to the l ...

Script on Tampermonkey executed prior to page loading

I am facing a challenge with hiding a specific section from an HTML page: <h1 data-ng-show="!menuPinned &amp;&amp; !isSaaS" class="logo floatLeft" aria-hidden="false"><span>XXX&nbsp;</span><span style="font-weight: bold;"& ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

Is it possible to create a type alias for a function with multiple signatures in TypeScript?

Is it feasible to generate a type alias for an overloaded function signature? For instance, I have a function as follows: function whenChanged(scope: ng.IScope, fn: ()=>void): ()=>void; function whenChanged(fn: ()=>void, truthy:any): ()=>void ...

Troubles arising while submitting data from AngularJS to Amazon S3

I am currently in the process of developing an application using the MEAN (MongoDB, Express, AngularJS, node.js) stack where I need to upload image files to Amazon S3. Here is my approach: Initially, an http get request is sent to my API which outlines th ...

Is regex the reason why the website isn't showing up properly on mobile devices?

I encountered an issue on my Vue.js website hosted on Firebase where a blank white page was displayed on mobile devices. After some investigation, I traced the problem back to two objects declared in the data function of one of my components: re: { you ...

Transformation of visuals with alteration of status

I am attempting to change the image of a door from closed to open when the status changes in my home automation dashboard. I need help with this task. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&qu ...

What is the best way to organize a Python array in alphabetical order?

I attempted to complete a task assigned by my friend with the goal of improving my knowledge, but I encountered an issue. The task involves sorting an array alphabetically, and despite searching extensively for a solution, I have been unable to find one. E ...

Setting up Storybook with Tailwindcss, ReactJS and Typescript: A comprehensive guide

What is the best way to configure Storybook to handle Tailwindcss styles and absolute paths? Just a heads up, this question and answer are self-documenting in line with this. It was quite the process to figure out, but I'm certain it will help others ...

A guide to implementing bounds with dynamic markers in react-leaflet

I have a functional react component that currently displays two static markers within a bounding box that fits both markers inside. However, I am trying to figure out how to pass an array of latitude and longitude values to dynamically display the markers ...

Updating / modifying code in a document using a Query

Just wondering, is it feasible to create a form that can be filled out to either write new code or replace existing code in a file? For instance, I have a result table with various outcomes. Rather than resorting to using a database or manually updating t ...

Unit testing with Jest involves creating mock implementations of IF conditions within functions to ensure complete code coverage

Currently, I am working with an API script stored in a file. const ApiCall = { fetchData: async (url) => { const result = await fetch(url); if (!result.ok) { const body = await result.text(); // uncovered line throw new Error(`Err ...

Adding a function to the Window in React & Next.js without using the onload event

Issue with External Script in React Next.js Project I am facing a problem with an external script within my React Next.js project. The script is located at . The script does not work correctly when navigating to the page using the next/link component fro ...

unable to access stored locations in XML file using JavaScript

I am attempting to retrieve a saved location from a database using JavaScript to read from an XML file. My goal is to add markers to a map based on these saved locations. Below is the XML code, can you identify any issues with my method of reading the XML? ...

Checking the validity of an input element with jQuery: How to determine if the valid or invalid pseudo-class has been applied?

Is there a way to check for the application of the CSS3 :valid or :invalid pseudo-class on an input element using jQuery? I want to verify if the form element has passed CSS validation before allowing the submit button to be enabled. Here are some methods ...

Achieving a balanced css navbar size that fits the page dimensions

I'm encountering an issue with my navbar where it gets distorted when the window size is too small. How can I make it shrink proportionally to fit the page? I've attempted several solutions, but they only reduce the text size without properly res ...

Optimal method for conducting Jasmine tests on JavaScript user interfaces

After exploring the jasmine framework for the first time, I found it to be quite promising. However, I struggled to find a simple way to interact with the DOM. I wanted to be able to simulate user interactions such as filling out an input field, clicking ...

Decipher encoded parameters utilizing the JavaScript encodeURIComponent method

I'm dealing with an issue in my application where text entered by a user is sent to the server as part of a URL to render an image. The text is encoded using the encodeURIComponent function, but I'm running into problems with certain characters l ...

Guide on how to add the details of a specific id just once using PHP or jQuery

Is there a way to ensure that newly added data from SQL is only appended once? The current script I'm using displays the newly added data from SQL, but it keeps appending the same data multiple times. For example, if I add 'test by thisuser&apo ...

Tips for merging Next.js configuration settings

My current configuration settings are as follows: module.exports = { images: { domains: [ "ticket-t01.s3.eu-central-1.amazonaws.com", "media.istockphoto.com", ], deviceSizes: [320, 375, 450, 540, 640, 750, 828, ...