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

Jest testing in a Vue child component is failing due to the presence of lodash

In this specific instance of my Vue app, I have globally loaded lodash as a Vue plugin in the main.js file: import _ from "lodash" export default function install(Vue) { Vue.prototype._ = _ Vue.mixin({ computed: { _: () => ...

Error in Jquery click function not being triggered

I'm in the process of developing an eCommerce platform where users can choose options and have their shopping carts automatically updated using jQuery. Users will be presented with a few radio buttons to select from, and as they make their choice, th ...

Ways to adjust .keyup based on the presence of a variable

I am currently in the process of constructing a search form that utilizes an ajax function within .keyup, which may have various arguments. I aim to determine if a specific argument should be included based on the presence of another value. Here is my curr ...

Using Express in Node.js to send a GET request to a different server from a Node route

When a client triggers a GET request by clicking a button on the index page, it sends data to a route that is configured like this: app.js var route = require('./routes/index'); var button = require('./routes/button'); app.use('/ ...

Execute Cheerio selector once the page has finished loading

Hey there! I'm trying to extract the URL value of an iframe on this website: I've checked the view page source but couldn't find the iframe. Looks like it's loaded after the page is fully loaded through JavaScript. Could it be that ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

Displaying the loading image only on the first result within a while loop

When a submit button is clicked on any result, the loading image below the button displays only for the first result in the while loop. For example, if I click the submit button on the first result, the loading image shows below it. However, when I click t ...

Managing the challenges of handling numerous AJAX post errors stemming from multiple form submissions

I am currently developing a PHP application that will be used to present multiple choice questions as well as text-based questions. The functionality I have implemented involves using Javascript code to submit user responses via ajax to the PHP server. He ...

"Unexpected Type Inference Issue: A variable initially defined as a string inexplicably transforms into 'undefined'

Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to method from the library). In an intriguing scenario, the variable type shifts to string | undefined within a for..of loop, whereas outside of the loop ...

A guide on utilizing Socket.io to efficiently transfer data to a specific client within a designated chat room

Can someone please advise on the correct way to send data to a specific client in a specific room using socket io? The code snippet I have been trying is: I am using the following command: socket.to(socket.id).emit('change', {data}) However, i ...

A guide to building your own live HTML editing tool

I'm currently developing a PHP website that allows users to enter text into a textarea, and have the input displayed in a table in real time for a preview of the result. I am seeking guidance on how to make this feature possible. I have come across w ...

Skipping certain key-value pairs during the conversion from JSON to Excel Worksheet using the XLSX library in JavaScript

I have a set of objects in JSON format within my JavaScript code and I am looking to transform this data into an Excel worksheet. Within the JSON structure, there are certain key-value pairs that I do not wish to include in the Excel output. For instance, ...

Can jQuery be used to change the functionality of a submit button, such as toggling between show, hide, and submit options?

I am having trouble toggling a button to either submit a form on click or reveal an input field, depending on whether the user clicks outside the input field to hide/collapse it. The issue arises when the user dismisses the input field and the submit butto ...

Discover the process for simulating a browser zoom using JavaScript

Is there a way to control the browser's zoom level using JavaScript? I decided to create my own solution to override the default browser zoom behavior. The current code works fine if starting from a scale of 1, but I'm facing an issue when alrea ...

Label dynamically generated from user input for radio button option

In my attempt to develop a radio group component, I encountered an issue where the value of one radio option needs to be dynamically set by an input serving as a label. While I have successfully created similar components before without React, integrating ...

Encountered an error message stating 'Unexpected Token <' while attempting to launch the node server

After adapting react-server-example (https://github.com/mhart/react-server-example), I encountered an issue with using JSX in my project. Despite making various changes like switching from Browserify to Webpack and installing babel-preset-react, I am still ...

Angular: No routes found that match the URL segment

I encountered an issue with my routes module where I am receiving the error message Cannot match any routes. URL Segment: 'edit-fighter' when attempting to navigate using the <a> link. The only route that seems to work is the champions-list ...

What is the correct way to integrate a HTML/CSS/JS theme into a Vue project effectively?

As a newcomer, I recently acquired a bootstrap theme that comes with HTML, CSS, and JavaScript files. My goal now is to integrate this theme into Vue in order to make it fully functional. The challenge I am facing is how to successfully incorporate the the ...

Deactivating and activating an HTML input button

So I was tinkering with this cool button: <input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/> I've been wondering, how can I conveniently control its state of being disabled or enabled? Initially, I attem ...

Receive a response in fragments from express on the browser

As I work on creating a progress bar to track long-running server-side tasks that may take up to a few minutes, I am exploring different methods to display the progress of each task. While WebSockets and interval polling are options, I prefer using long-po ...