What is the functionality of nested object getters in retrieving a property name from a nested object while constructing the object?

Seeking help to retrieve a nested property name in an object while constructing the object.

What could be the issue here? How can I obtain the desired output: 'c' from the nested object?

Source of reference: MDN documentation
const obj = {
  log: ['a', 'b', 'c'],
  get latest() {
    return this.log[this.log.length - 1];
  }
};

console.log(obj.latest);
// Expected result: "c"
// Current result: "c"

The provided example above is functional as expected.

However, my goal is to introduce nesting (obj.level1). Here is where I encounter difficulties.

First modification attempt: unsuccessful
const obj = {
  level1: {
    log: ['a', 'b', 'c'],
    get latest() {
      return this.log[this.log.length - 1];
    }
  }
};

console.log(obj.latest);
// Desired outcome: "c"
// Result received: undefined
Second modification attempt: unsuccessful
const obj = {
  level1: {
    log: ['a', 'b', 'c'],
    get latest() {
      return this.log[this.level1.log.length - 1];
    }
  }
};

console.log(obj.latest);
// Desired output: "c"
// Output obtained: undefined

Answer №1

The newest function is located within the first-level. This code snippet demonstrates how you can access it:

console.log(data.first-level.newest)

If this is not your desired outcome, consider structuring your object as shown below.

const data = {
  first-level: {
     records: ['x', 'y', 'z']
  },
  get newest() {
    return this.first-level.records.at(-1);
  }
};

Answer №2

Your changes to obj no longer include the latest getter. This is now located in the child object level1, so be sure to log obj.level1.latest.

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

Having trouble using functions with dynamically loaded content via AJAX in JQuery

I am facing an issue with my code. I am trying to dynamically fetch some data and display it. I have checked the request using firebug and it seems to be successful, but the problem arises when I try to execute the activeImage() function. The images are no ...

Struggling to make my JavaScript function work across different products

As a beginner in Javascript, I am facing an issue with a button that should open a 'window' when clicked. While it works for product 1 (chili oil), the same functionality is not working for product 2 (raspberry ratafia). Initially, the function ...

Difficulty encountered when creating step definitions - Implementing Cucumber and Appium using JavaScript

I am currently embarking on a project that serves as more of a proof of concept. For me, this is a POC since I am aware that similar projects have been executed before. My focus revolves around working with Cucumber.js, Appium Server/Client, Node, and Jav ...

Query JSON using PHP without specifying element values

JSON data is presented in the following format { 73: { id: 74, title: "39", body: "11100000000000000000#IS#2.5", created_at: "2018-04-23 21:19:19", updated_at: "2018-04-23 21:19:19" } } I am looking for a ...

What is the method of adding a child to the outerHTML of the parent element instead of within it?

Is there a way to use the outerHTML method on a parent element to append a child element so that the icons appear outside of the targeted element rather than inside it? The current code snippet shows the icons inside the box, but I want them to be placed o ...

Is there a way to determine the duration of a function's execution using jQuery?

In my script, I have implemented jQuery functions such as A(), B(), and C(). Each of these functions involves making Ajax calls to various external sites. I am interested in measuring the runtime of each function, ideally in milliseconds. To analyze my co ...

incorporating my unique typographic styles into the MUI framework

I'm currently working on customizing the typography for my TypeScript Next.js project. Unfortunately, I am facing difficulties in configuring my code properly, which is causing it to not work as expected. Can someone kindly provide assistance or guida ...

No data found in response from gRPC Server

Despite my efforts, the JSON object returned from a callback in my gRPC server remains empty. Following a tutorial similar to this one, I have made some modifications such as using a SQLite3 server instead of knex and focusing on the listProducts method. ...

Creating a TypeScript rule/config to trigger an error when a React Functional Component does not return JSX

I've encountered a recurring issue where I forget to include a return statement when rendering JSX in a functional component. Here's an example of the mistake: const Greetings = function Greetings({name}) { <div>Greetings {name}</div& ...

Is it possible to trigger an AJAX function from a popup using the "Colorbox - a jQuery lightbox plugin"?

Currently, my website utilizes PHP, Smarty, jQuery, and the Colorbox jQuery plugin. All necessary files have been included in the index.tpl file, ensuring smooth functionality without any issues. Within a Smarty template file, I have implemented a Colorbo ...

Creating a cascade of falling balls with a single click: Here's how!

I'm currently working on a project where I have a ball dropping from the cursor location and redropping when the cursor moves to another position. However, I want to be able to create a new ball every time I click the mouse. I attempted the following ...

What distinguishes CLIENT_SECRET from oauth2client credentials in Google Sheets API json files?

I successfully implemented the Google Sheet Python API by following their Quickstart guide (https://developers.google.com/sheets/api/quickstart/python). Here is the code snippet that made it work: def get_credentials(): """Gets valid user credentials ...

Execute multiple JavaScript files dynamically by utilizing the same npm run command

My directory structure: app Model user.js post.js Contents of my package.json file: "scripts": { "migrate": "node ./app/Model/" } I am looking to execute JavaScript files via command line in a dynamic manner. For example: npm run migr ...

What are the steps to fix a timeout error with React.js and socket.io acknowledgements?

My setup includes a Node.js server and a React.js client application. Data is exchanged between them using socket.io, but I'm running into an issue with implementing acknowledgment. Whenever I try to implement acknowledgment, I receive a timeout error ...

Display modal scroll functionality when a modal window is activated

Can someone explain to me why my solution isn't working? I'm trying to hide the scroll on my page when a modal is opened and allow scrolling within the modal. It would also be great if there could be a slide up & down effect. I attempted to achi ...

modify handler for selecting input item in react JS

I am working on mapping option select data from an API, but I am having trouble changing the value of the select input. I have tried using a handler for change, but the input value remains fixed. Can someone please help me identify what error might be pres ...

Invoking a shared controller function in AngularJS from a separate controller

My main objective is to retrieve the current logged-in user by calling back to the server when a visitor lands on the site while still logged in. The challenge I face is determining which controller will be active since it's uncertain which page the v ...

Include in assortment if not already in stock

I have a document embedded within my collection labeled as likes: { "_id" : ObjectId("57a31e18fa0299542ab8dd80"), "created" : ISODate("2016-08-04T10:51:04.971Z"), "likes" : [ { "user" : ObjectId("1"), "date" : ...

Query MySQL to retrieve rows that contain a specific value in the json_column field

In my MySQL table test, there is a column trip_info that stores JSON data. Here is an example of the JSON structure: { "trips": [{ "id": "261213_0", "type": "CD", "truck&quo ...

Can the output of the "npm run build" command, which consists of static files, be transformed back into a fully functional project?

I possess static JavaScript build files without access to the source code that produced them. Unfortunately, the previous developer is no longer around to provide insight. Is there a way to deconstruct these files? ...