What is the method for retrieving values from an object using keys that are subject to change?

Here is the code snippet I am working with:

    bodyLength.forEach((el, i) => {
      console.log(`${values.bodyTitleEn2 + i.toString()}`);

      body.push({
        title: [
          {
            key: 'en',
            value: values.bodyTitleEn + i,
          },
          {
            key: 'ku',
            value: values.bodyTitleKu + i,
          },
          {
            key: 'ar',
            value: values.bodyTitleAr + i,
          },
        ] ...

The variables values.bodyTitleEn, values.bodyTitleKu, and values.bodyTitleAr have numbers at the end of them (such as values.bodyTitleEn0, values.bodyTitleEn1, values.bodyTitleEn2). I also have an array called bodyLength which contains the number of bodyTitle[En] elements. I am trying to dynamically add the number at the end using values.bodyTitleEn + i, but it throws an error saying values.bodyTitleEn is undefined. This is because bodyTitleEn does not exist in the object without the number at the end. How can I go about achieving this? Thank you.

Answer №1

To include the number, simply append it in this manner:

values[`bodyTitleEn${i}`]

The code snippet above attempts to retrieve the value associated with the keys bodyTitleEn0, bodyTitleEn1, and so on.

When you write values.bodyTitleEn + i, you are essentially trying to concatenate the number to the value retrieved by values.bodyTitleEn. However, as you've noticed, the 'values' object does not contain the key bodyTitleEn, and even if it did, that is not the desired functionality.

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

jQuery's conditional always evaluates the first condition

One of the elements in my jQuery code is a conditional function designed to display a specific message with its own style when necessary: function msg(type, text) { if (type="success"){ $('.messageDisplay').attr('class', &a ...

Tips for creating a unique custom UI headline using ReactJS, CSS, and bootstrap

Looking to create a design that is responsive in ReactJS using Bootstrap or CSS if needed. I need assistance with placing separators between columns and ensuring the values of each label are aligned in the same column but on the next line. The layout shoul ...

Iterate through a generic array to populate a table using ng-repeat

In the scenario I'm currently facing, I am working on creating a common reusable table structure using a directive. The goal is to display different JSON data in both the table header and body. Below is the controller code: angular.module('plun ...

Reposition the checked box to the top of the list

My goal is to click on each item, and the selected item should move to the top of the list and be rendered at the top. However, I encountered an issue where when clicking on an item, it moves to the top but the item that replaces it also gets checked. Bel ...

Error message in JS and HTML is totally bizarre

My expertise in JavaScript is very limited, so the terms I use might not be entirely accurate. However, I'll do my best to explain the issue at hand. I'm facing a peculiar problem... I've been attempting to modify someone else's JS scr ...

"Here's a neat trick for assigning the value of a div to a text box without any identifiers like id or

I needed a way to transfer the value of a .item div into an empty textbox without any specific identifier. Then, when the input loses focus, the value should be sent back to the original .item div. $(document).on("click", ".item", function() { $(this) ...

What is the best way to display the complete text or wrap a menu item in an Angular Material menu?

Is it possible to display the full text of a menu item instead of automatically converting it to ellipses or breaking the word? I've tried various CSS methods without success. Any suggestions? https://i.stack.imgur.com/3l7gE.png #html code <mat-m ...

Ensuring a consistently positioned footer at the bottom

I understand that this might not seem like a significant issue, but I'm encountering some difficulties. In my main.html file, there are three divs. The first div contains the navigation bar, the second div is an "empty" div that uses JQuery/Javascript ...

How can I dynamically adjust the stroke length of an SVG circle using code?

In my design project, I utilized Inkscape to create a circle. With the fill turned off, only the stroke was visible. The starting point was set at 45 degrees and the ending point at 315 degrees. After rotating it 90 degrees, here is the final outcome. < ...

The function cannot be called because the type does not have the appropriate signature for invoking. The specific type lacks compatible call signatures, as indicated

Encountering an issue while attempting to utilize a getter and setter in my service, resulting in the following error message: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures 2349 t ...

Refreshing chord chart information from a JSON source in d3.js

I have two functions that are responsible for creating and drawing a D3 chord diagram representing the netflow between different IP addresses in our network. Function 1 (for creating the chord diagram) function createChords(jsonURL, containerID, tooltipI ...

Error: Unable to convert Mongoose object to ObjectId

Currently tackling an issue with my small blog app and I seem to be stuck at this error- { "message": "Cast to ObjectId failed for value \" 597c4ce202ca9c353fc80e8a\" at path \"_id\" for model \"Blog\"", "name": "CastErr ...

Trouble with implementing Ajax in Express and jquery

My app has a browse page where users can add items as owned or wanted. Currently, when adding an item it redirects back to the general /browse page. However, I want the page to not refresh at all. I'm attempting to achieve this with ajax, but as a beg ...

What is the method for sending raw put data using the request npm package in a Node.js environment

How can I hit an API using the "require" npm package in Node? The API requires raw PUT data instead of PUT fields. Can anyone please guide me on how to achieve this using the request npm package? For example, here is the raw PUT data that needs to be sent ...

Transforming the FormData() format into a jQuery structure

Hey there! I've been doing some research online about uploading files using JavaScript, and I stumbled upon some great resources, including this one https://developer.mozilla.org/en-US/docs/Web/API/FormData. I have a script that uploads an image to th ...

Facing an issue with displaying a component error in a mat-form-field in Angular 9

I am looking to develop a shared component for displaying errors in Angular Material. Here is my shared component pfa-share-error: <mat-error *ngIf="fieldErrors(fieldName).required && fieldErrors(fieldName)"> Required </mat-err ...

Balancing asynchronous tasks - masteringlearnode - program that initially succeeded but eventually faltered

node version: v4.4.3 npm version: 3.8.9 Error output Your entered data does not match the expected values. ──────────────────────────────────────────────── ...

Looking to update the URL from another component?

My current project is using Angular 6 and I am working on creating a list of buttons on the left panel such as "Ice cream", "Pop corns", and more. The goal is for users to click on these buttons which will then change the URL of the add button located in t ...

Is the iCheck feature designed to block all parent click events?

I've developed an "interaction tracker" system that collects anonymous data on clicked page elements. By implementing an event listener for clicks on the body, I can track interactions with any element on my site successfully. However, interestingly ...

Setting up route handlers in Node.js on a pre-initialized HTTP server

Is there a way to add route handlers to an http server that is already instantiated? Most routers, including express, typically need to be passed into the http.createServer() method. For instance, with express: var server = http.createServer(app); My r ...