Loop through every item in Typescript

I am currently working with the following data structure:

product: {
    id: "id1",
    title: "ProductName 1",
    additionalDetails: {
        o1: {
            id: "pp1", 
            label: "Text",
            content: [{ id: "ppp1", label: "Tetetet" }]
        },
        o2: {
            id: "pp2", 
            label: "Text2", 
            content: [{ id: "ppp2", label: "Tetetet2" }]
        } 
    }
}

I have been attempting to iterate through each object inside `additionalDetails`, but for some reason, it is not working as expected. Here is my code snippet:

Object.keys(product.additionalDetails).forEach((key: string) => {
  const additionalDetail = product[key];
  const idLabel: string = additionalDetail.id;
  const label: string = additionalDetail.label;
  const contentId: string = additionalDetail.content[0].id;
  const content = additionalDetail.content[1].label;
});

Unfortunately, this code snippet does not seem to be functioning correctly. Can anyone help point out what I might be missing or doing wrong?

Answer №1

There are two errors to correct:

Replace product[key] with product.additionalDetails[key]

and

additionalDetail.content[1] does not exist (since content is an array with only one element inside)

product= {
  id: "id1",
  title: "ProductName 1",
  additionalDetails: {
    o1: {
      id: "pp1",
      label: "Text",
      content: [{
        id: "ppp1",
        label: "Tetetet"
      }]
    },
    o2: {
      id: "pp2",
      label: "Text2",
      content: [{
        id: "ppp2",
        label: "Tetetet2"
      }]
    }
  }
}

Object.keys(product.additionalDetails).forEach( key => {
  const additionalDetail = product.additionalDetails[key]; // <-- Here
  const idLabel = additionalDetail.id;
  const label= additionalDetail.label;
  const contentId = additionalDetail.content[0].id;
  // const content = additionalDetail.content[1].label;  // <-- content[1] Doesn't exist
});

Answer №2

Loop through the attributes within additionalDetails using either Object.keys, Object.values, or Object.entries.

const item = {
  id: "id2",
  name: "ItemName 2",
  additionalDetails: {
    a1: {
      id: "aa1",
      description: "Description",
      specifications: [{
        id: "s1",
        feature: "Feature 1"
      }]
    },
    a2: {
      id: "aa2",
      description: "Description 2",
      specifications: [{
        id: "s2",
        feature: "Feature 2"
      }]
    }
  }
}

for (const [key, value] of Object.entries(item.additionalDetails)) {
  console.log(`Detail ${key} has description ${value.description}`);
}

Answer №3

If you want to retrieve the id of an array item, follow these steps:

o1: {id: "pp1", label: "Text", content: [{id: "ppp1", label: "Tetetet"}]},

To access the content id, use the following code:

First, specify the index of the array containing the object with the content id:

const contentId: string = additionalDetail.content[0].id;

Make sure to define additionalDetails using const as well.

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

Passing data back from an asynchronous function to its parent function in Node.js

Exploring the world of asynchronous programming is a new adventure for me as I delve into implementing Twilio video calls through Node.js. I've been grappling with calling a server-side function that in turn invokes another asynchronous function retu ...

What is the method for determining the number of unique tags on a webpage using JavaScript?

Does anyone have a method for determining the number of unique tags present on a page? For example, counting html, body, div, td as separate tags would result in a total of 4 unique tags. ...

Is it possible to use a server action in Next.js to both retrieve data and refresh the page?

I am currently working on developing a web application using Next.js (13.4.9) and I intend to utilize server actions. These server actions will involve sending data to the server, which will process the data and return a string back to me. The challenge I& ...

Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call. <script type="text/javascript"> $(document).ready(function() { $('#call').click(function () { $.ajax({ type: "post", ...

Is there a way to implement multiple "read more" and "read less" buttons on a single page?

I am currently working on a rather large project and I am encountering some issues with the read more buttons. As someone who is fairly new to JavaScript, I am still grappling with the concepts. While I have managed to make the function work for the first ...

The JavaScript confirm function will provide a false return value

Is it necessary to display a confirmation message asking "Are you sure ..."? I have implemented the message, but the function return false; is not working when the user clicks NO. <script> function confirmDelete(){ var answer = confirm("Are you su ...

How to optimize the utilization of Javascript variables within a Jquery function?

Currently, I am working on implementing an HTML5 min and max date range function. Initially, I wrote the code using variables and then embedded them in the correct attribute locations. However, after reviewing my code, my client (code reviewer) suggested ...

Combining two items from separate arrays

How can I efficiently merge objects that share the same index in two different arrays of objects? Below is the first array const countries = [ { "name": "Sweden", "nativeName": "Sverige" }, ...

Query regarding timing in JavaScript

I recently started learning JavaScript and I am facing a challenge with running a check to determine if it is daylight. Currently, I am using Yahoo's weather API to retrieve information about sunrise and sunset times. The issue I have encountered is h ...

Error in React Native Navigation: Passing parameters is not functioning properly

Within my React Native application, I have meticulously established the following routes in my app.js: export default class App extends Component { render() { return ( <NavigationContainer> <Stack.Navigator initialRouteName=&qu ...

Tips for accessing the return value from a method outside of its containing function

Having recently started using Angular, I'm encountering an issue with retrieving a return value from a function that I have implemented within another one. private validateKeyterm(): boolean { const val = this.form.value.term; if ...

Tips for refining TypeScript discriminated unions by using discriminators that are only partially known?

Currently in the process of developing a React hook to abstract state for different features sharing common function arguments, while also having specific feature-related arguments that should be required or disallowed based on the enabled features. The ho ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

Exploring the power of Vue.js reactivity using Object.defineProperty in a TypeScript environment

Currently, I am in the process of developing a TypeScript class to manage form submissions and handle server errors: export default class Form<Model> { private readonly original: Model private changes: Partial<Model> constructor(d ...

Combine iron-page and bind them together

Recently, I've started learning about Polymer and I want to bind together paper-tabs and iron-pages so that when a tab is clicked, the content loads dynamically. After going through the documentation, this is what I have tried: <app-toolbar> ...

How to dynamically add events to a JQuery FullCalendar using a loop

When utilizing the jQuery full calendar, I need to dynamically set events based on data obtained from a database. To achieve this, I am using data attributes to assign values and then display them on the calendar. Below is an example of my html twig code: ...

JavaScript OOP Function call not functioning in IE9

When using IE9, a JavaScript OOP Function call does not seem to work for me. Here is my code snippet: var newobj = new SAObject(); <input onclick="newobj.function()" /> Upon clicking the button, nothing happens. No alert is displayed, and it seem ...

Activate a particular panel within the leftPanel using PDFNet Webviewer

When using disableElements in the setQuickBarPanelContents() function, I am able to remove 2 of the 3 panels from the leftPanel: setQuickBarPanelContents() { this.instance.disableElements(['notesPanel', 'notesPanelButton', &apos ...

Is it possible to include additional transformations to a div element?

Is it possible to add additional rotation to a div that already has a transform applied? For example, can I do the following: <div style="width: 200px; height: 200px; background-color: red; transform: rotateX(90deg) rotateY(10deg)" id="myDiv">< ...

Encountering a 'DiscordAPIError: Unknown interaction' error while attempting to share details about a command

As I work on a slash command to deliver information about a specific command when users type /help, I encountered an error when trying to add multiple commands: E:\v13\node_modules\discord.js\src\rest\RequestHandler.js:298 ...