Iterate over an array of objects to showcase the property values within an HTML tag using JavaScript

I am a beginner in JavaScript and I am currently working on an exercise. My goal is to iterate through an array of objects within another object, map the index values from one object to the id values in another object, and based on that, perform a certain operation. Below is my object:

obj= {
    "text": [{
        "id": 0,
        "name": "aaa"
      },{
        "id": 1,
        "name": "bbb"
      },{
        "id": 3,
        "name": "ccc"
      },{
        "id": 4,
        "name": "ddd"
      }],
    "content": [
      {
        "id": 123,
        "index": 0
      },{
        "id": 1232,
        "index": 2
      },{
        "id": 12333,
        "index": 3
      }
    ]
}

This section has two parts:
1) To display the values of the name property within the text object as follows:

aaa
bbb
ccc
ddd
eee
fff

2) I aim to insert a - after every group of name values based on the index provided within the content object. Essentially, I need to match the index values from the content object to the id values inside the text object and add a - accordingly. In this case, with indexes of 0, 2, and 3, the output should appear like:

aaa
bbb
-
ccc
-
ddd

Here is the code I have for part 1 so far:

function string() {
  var arr = obj.text;
  var output = '';
  for(var i=0; i<arr.length; i++) {
    output += '<div>'+ arr[i].text + '</div>';  
  }
  document.getElementById("container").innerHTML =  output;
}

I would appreciate any help regarding part 2. Do you have any suggestions?

Answer №1

It appears to be a straightforward issue to me, so here's a proposed solution. However, I can't help but wonder if there's a subtle detail in the question that I might have overlooked.

const
  obj = { text:   [ { id: 0, name: "aaa" } 
                  , { id: 1, name: "bbb" } 
                  , { id: 3, name: "ccc" } 
                  , { id: 4, name: "ddd" } 
                  ] 
        , content:[ { id: 123,   index: 0 } 
                  , { id: 1232,  index: 2 } 
                  , { id: 12333, index: 3 } 
                  ] 
        } 

function string()
  {
  let a_text    = obj.text
    , a_content = obj.content
    , Container = document.getElementById("container")
    , c_Index   = 0

  if ( a_content[c_Index].index === 0 ) c_Index++
  
  for(let i=0; i<a_text.length; i++)
    {
    if (i >= a_content[c_Index].index)
      {
      c_Index++
      let barDiv = document.createElement('div')
      barDiv.textContent = '-'
      Container.appendChild(barDiv)
      }

    let NewDiv = document.createElement('div')
    NewDiv.textContent = a_text[i].name
    Container.appendChild(NewDiv)
    }
  }

string()
<div id="container"></div>

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

Wait for all asynchronous functions in Node.js to finish before proceeding with the remaining code

I am facing an issue in my code where I have 2 for loops executing the same async function, but I need the code to wait until both loops finish executing before proceeding. Here is a snippet of my code: for(var a = 0; a < videoIds.length; a++){ ...

What is the best way to indicate the selected item in the Menu List using Material UI React?

I am attempting to dynamically style the menu list items by toggling the selected prop between true and false. In order to achieve this, I am utilizing the onClick method to capture the event.target.name, update the state of the corresponding value associ ...

Is Socket.io combined with Redis the best architecture for an interactive gaming experience?

My current setup involves a NodeJS scaling architecture with Redis, specifically designed for a real-time multiplayer game. However, I'm facing challenges in configuring separate lobbies for players, as the load balancer assigns users to different ser ...

Using jQuery to trigger several setTimeout() functions in succession

I'm struggling to grasp the concept of jQuery promises. To delve into this topic, I have put together the following code snippet inspired by a discussion on StackOverflow. let functions = [ function () { setTimeout(function () { console.log("func ...

"Troubleshooting: Jquery Draggable Function Fails to Execute

I'm currently working on a JSP page where I am attempting to make the rows of a table draggable. Despite multiple attempts and combinations, I have been unable to make any elements draggable. The rows are appended after an AJAX call, but still no succ ...

Using JQuery to find the nearest element and narrowing down the search to its child elements

In my program, I have 3 forms identified by form1, form2, and form3. Each form contains its own set of dropdown lists named drop1 and drop2, along with a submit button. When the submit button is clicked in any form, it checks which option was selected from ...

What is the best way to choose the element directly beneath a specific element using jQuery?

I am facing a challenge where I need to manipulate HTML content using only jQuery, without changing the original structure. The requirement is to display and slide down content with a specific class (current) upon clicking on an h1 tag. However, I am strug ...

The Discord.js guildMemberUpdate event: Everything you need to know

I am currently working on creating a welcome message bot using Discord.js. The goal is to have the bot send a welcome message through a webhook in a specific channel when a member gains access to it. Here's what I have so far: client.on("guildMe ...

Sending parameters in GraphQL with Typescript results in an empty set of curly braces being returned

I am new to learning GraphQL with Typescript and I am trying to pass an argument in a GraphQL function to return something dynamically. I have been struggling with this issue for the past hour and could not find any solutions. Here are the relevant code sn ...

The ng-change functionality of Angular radio buttons only functions correctly the first time it

I am struggling to comprehend why the angular ng-change function is only being called on the first click. Take a look at this example: http://jsfiddle.net/ZPcSe/5/ The function in the provided example is triggered every time the radio selection is change ...

The JSONP file can be successfully retrieved through an AJAX request in the console, however, the data does not display when attempting

Currently attempting to send an ajax request utilizing the following code snippet: $.ajax({ url: "http://mywebsite.com/blog/json", dataType: "jsonp", jsonpCallback: "jsonpCallback" }); function jsonpCallback(data) { console.log(data); } E ...

Synchronizing code paths that involve both ajax and non-ajax functions can be achieved by

My website features a basket functionality where users can enter an author's name and see the available books. After selecting desired books, they have the option to click on another author for more selection. The displayed list includes books by Step ...

Steps to create an automatic submission feature using a combobox in HTML5 and then sending the retrieved data back to the HTML file

Here is the code snippet I've been working on: <strong>Station Name</strong> <!--This portion includes a combobox using HTML5 --> <input type=text list=Stations> <datalist id=Stations> <option>Station1</opt ...

How can NodeJS implement ThreadLocal variable functionality without relying on req and res.locals?

In a specific situation, I am required to handle business logic and logging for each request separately. This means that the data stored should not overlap with data from other requests. Using res.locals or req objects is not an option in this case becaus ...

Problem with Material-UI Drawer

Is there a way to make this drawer stay fixed on the page like a sticker and remain active without moving when scrolling? I've tried using docked={false}, but it makes the whole page inactive except for the drawer. Any suggestions on how to solve this ...

Troubleshoot: Dropdown menu in Materialize not functioning (menu fails to drop down

I am currently incorporating Materialize to create a dropdown button in my navigation bar. However, I am facing an issue where nothing happens when the button is clicked. Here is a snippet of my code: <head> <meta charset="UTF-8"> <!-- ...

CORS blocked the JavaScript Image's request

I am encountering an issue with my code that involves capturing selected divs using the HTML2Canvas library. However, when I try to download the captured image file, it is not working as expected. The error message I keep receiving is "Access to Image at ...

JSF CommandLink malfunctions on Firefox when reRendering an entire form

I am currently working on a JSF 1.2 application (Sun RI, Facelets, Richfaces) that was previously designed only for IE6 browsers. However, we now need to extend our support to include Firefox as well. On one of the pages, there is a form with a button tha ...

Tips for integrating jwt token into axios request

I am facing an issue with my backend endpoint. I can successfully retrieve a list of customers using jwt token on Postman, but when I try to fetch the list from a React app using axios get request, it fails. After reading through this question, I implemen ...

Deploying CSS/JS files in Magento 2 is a crucial

Hello, I recently set up magento2 with the sample data included. After attempting to deploy static css/JS using the command php bin/magento setup:static-content:deploy, I didn't receive any errors but the issue persists. Additionally, I am unable to l ...