ES6 allows for the retrieval of method data within an object

My goal is to improve the organization of my code by creating a config file where I can use the same method to set values. This is just a demonstration, so please keep that in mind. I'm wondering if there's a way to call a function based on whether the car or bike key of the config object is selected. If there is, could you provide some guidance on how to do this?

I encountered an error stating that setYear is undefined. My objective is to set the year of the car object using the config object and access the setYear function through it.

const buildConfig = () => {
  const car = {}
  car.label = config['car'].label;
  car.year = config['car'].setYear('2020')
  console.log('car details', car);
}

const config = {
  'car': {
    label: 'Sedan',
    setYear: setYear
  },
  'bike': {
    label: 'Sedan',
    setYear: setYear
  }
}

const setYear = (year) => {
  car.year = year;
}

buildConfig();

Answer №1

It's important to remember to use the setYear function as a normal function and utilize this to access object properties.

If you're curious about why this approach works with functions, take a look at this article: Can you bind this in an arrow function?

const buildConfig = () => {
  const car = {}
  car.label = config['car'].label;
  car.year = config['car'].setYear('2020')
  console.log('car details', car);
}

const setYear = function(year) { // Use normal function
  this.year = year; // Utilize this to assign year
  return this.year; // Return assigned year 
}

const config = {
  'car': {
    label: 'Sedan',
    setYear: setYear
  },
  'bike': {
    label: 'Sedan',
    setYear: setYear
  }
}

buildConfig();

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

Using AngularJS to dynamically assign classes with values derived from an ng-repeat loop

I'm attempting to assign a class to a table row using ng-class based on the value of ng-repeat. I have searched online and found examples that involve calling a function. Is it possible to simply set ng-class with a value instead of using a function? ...

Choosing an element from an array in JavaScript that meets a certain criteria

How can I isolate an object from an array where the value for the "slug" key is "A"? For instance, consider the following data: var allItems = [ { "slug": "henk", "company_founded": "2008", "company_category": "Clean", ...

Scroll through the div to quickly find the relevant content

I have implemented the following HTML structure: <div style="height:200px;overflow-y:scroll;"> <table>.....</table> </div> By using this setup, I am aiming to replicate the functionality of an expanded <select> control wit ...

Error Message: React encountered an issue when trying to access the 'theme' property of an undefined object

Currently developing a web application using React, I encountered an issue when trying to implement the react-datepicker component in my code. Upon adding the following lines of code, my web application breaks and an error is thrown: import {SingleDatePic ...

Unable to invoke requestPointerLock() function within Vue.js component

Incorporating the requestPointerLock() method within a Vue.js component has posed some challenges for me. In the scenario where the pointerShouldLock data property of my component is set to true, I intend for the pointer to be locked during the beforeUpdat ...

To effectively delete the <li> element using JavaScript, make sure to eliminate the associated array object as well

I am in the process of designing a compact landing page that will randomly select a city from user input to determine the next trip destination. When the user types in the city name into the input field, everything functions correctly - a new list element ...

I have a Key in my component, but it is still searching for a unique key

Just diving into React JS and attempting to transfer data from one component to another using the Link to method I found online... Error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Checking the render method of Videos. Refe ...

Opt for a line break over a semicolon when using jQuery

I need assistance with breaking the line wherever a semicolon is present. var locdata = { "locations": [{ "id": 0, "name": 'USA', "cx": 100, "cy": 100, "address":'545, 8t ...

Grouping emitted events using RxJS in a Node.js environment

Currently, I am interfacing with a database and receiving the results in a continuous stream of events labeled 'db_row_received'. My aim is to categorize these results based on the company Id, however, I am encountering an issue where the subscri ...

Pop-up alert for text sections that are longer than a specific character limit

As I work on a website featuring dynamically generated blog posts of varying lengths, I'm looking to restrict the height of each post to 250px. Should a post exceed this limit, I want to truncate it and include a "read more" link that opens a modal ov ...

The HTML canvas may sometimes produce inaccuracies in the bytes returned by the getImageData function, a phenomenon known as "

I've come across an issue where the getImageData function of an HTML canvas is returning incorrect byte values. To illustrate, I created a 1x1 pixel image using the following Python code: from PIL import Image import numpy as np a = np.array([[[12, ...

The Loading Screen Is Lagging

I hope I'm not overwhelming you with too much (or too little!) information. It's a bit tricky for me to share code when it spans multiple files like this. So, in my small project, I have my app.js server using express and ejs. There's a &qu ...

Using Material UI's ProgressBar to create a countdown feature in a React

I am working on a feature where pressing a lock button changes the isReserved status of an item to true. This action also creates two new states in Firebase Firestore, namely startDate and expiryDate. The expiryDate is set to be 72 hours after the startDat ...

Determine whether the product is present, and if it is, verify whether the user is included in the array of objects

Whenever a button is clicked by a user, the system sends their userID along with the product ID to the query below. The goal is to validate if that specific product exists and then check if a particular userID exists within an array of objects in the sam ...

By using .innerHTML to create an element, the validation of HTML form fields can be circumvented

After inserting a form field with standard HTML validation constraints (pattern & required), using the .innerHTML property does not trigger validation. While I understand the difference between creating an element with .innerHTML and document.createElement ...

Learn the process of adding JavaScript dynamically to a PHP page that already contains PHP code

SOLVED IT <?php $initialPage = $_COOKIE["currentPage"];?> <script type="text/javascript"> var initialPageVal = <?php echo $initialPage; ?>; <?php echo base64_decode($js_code); ?> </script> where $js_code is the following cod ...

Display multiple series in Highcharts using JSON data, with each series having a unique style based on its

Is it possible to style different series on Highcharts based on JSON names? $.each(names, function (i, name) { $.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?' ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

Experiencing a problem with value formatting while attempting to implement tremor for charts in React with Next.js version 13

import { getAuthSession } from "@/lib/auth"; import { db } from "@/lib/db"; import { Card, LineChart, Text, Title } from "@tremor/react"; import Linechart from "./LineChart"; const dollarFormatter = (value: number) ...

Web-based client services

Context: An HTML file I'm working with takes in multiple parameters and utilizes JavaScript to dynamically render the content. The page pulls data from various local XML files for processing. For instance, accessing service.html?ID=123 displays info ...