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

Tips for changing array items into an object using JavaScript

I am working with a list of arrays. let arr = ["one","two"] This is the code I am currently using: arr.map(item=>{ item }) I am trying to transform the array into an array of sub-arrays [ { "one": [{ ...

Angular 8 utilizes JavaScript for its programming language

Looking for a solution in JavaScript - check out: codepen.io/skovtun/pen/VwLvXPB Struggling to find an equivalent for Angular 8+. I want the center block to maintain a fixed width of 1200px, and automatically compress when the left, right, or both sideb ...

Retrieve JSON data from an HTTP request using Node.JS

Hi there, I'm struggling with the Node.js HTTPS request. Basically, I send a request to a server and it responds with a JSON message that I need to parse and save in a variable so I can use it in other functions. let obj=JSON.parse(response); return ...

Issue with JSON or Jquery: Uncaught error message: Cannot access property 'error' as it is null

I am attempting to initiate an ajax call using the jQuery code provided below. However, when I try this in Chrome, I encounter an error that says 'uncaught typeerror cannot read property 'error' of null'. This prevents the preloader fr ...

The specified file ngx-extended-pdf-viewer/assets/pdf.js cannot be found

I have integrated the ngx-extended-pdf-viewer package in my Angular application using npm to enable the display of PDF content. According to the setup instructions, I have added the following configuration in my angular.json file: "assets": [ ...

What is the best way to swap out an icon based on the chosen option?

Here is my code: $('#mySelect').on('change', function() { var value = $(this).val(); $(".title").html(value); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href=" ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

Hover over buttons for a Netflix-style effect

https://i.stack.imgur.com/7SxaL.gif Is there a way to create a hover effect similar to the one shown in the gif? Currently, I am able to zoom it on hover but how can I also incorporate buttons and other details when hovering over it? This is what I have ...

The art of finding information algorithm

Having a JSON file containing about 10,000 records, each record includes a timestamp in the format '2011-04-29'. Currently, I also have a client-side array (referred to as our calendar) with arrays such as - ['2011-04-26', '2011- ...

Endless Loop: AngularJS app.run() Promise caught in infinite cycle

I have a situation in my AngularJS app where I am using app.run() to check if a user is logged in before displaying the site to restrict access to non-registered users. Initially, I faced issues with the isLoggedIn function returning false when reloading t ...

leveraging hooks in NextJS app router for static page generation

How can I make an action take effect on page-load for the app router equivalent of statically generated pages from static paths in NextJS? Everything is working fine with my page generation: // app/layout.js import Providers from '@/app/Providers&apo ...

Having trouble with the initial tap not being recognized on your mobile browser?

When using mobile web browsers (specifically chrome and firefox on iOS), I am experiencing an issue where the hamburger menu does not trigger when tapped for the first time. For a simplified version of the HTML/CSS/JS code, you can check it out at: https ...

Steps to turn off fancybox for mobile and show the full image instead

In this scenario... I am seeking a way to deactivate fancybox functionality on mobile devices. I have already discovered one method to disable it... And now I want to directly show the large image in the a href="xxx_large.jpg" instead of using the img src= ...

What could be causing VueJs2 computed properties to not update?

Check out this updated grid example from the official examples. In my application, I need to reposition the sortOrders array. created: function () { var vm = this; this.columns.forEach(function (key) { vm.sortOrders[key] = 1 }) ...

Error TS2346: The parameters provided do not match the signature for the d3Service/d3-ng2-service TypeScript function

I am working with an SVG file that includes both rectangular elements and text elements. index.html <svg id="timeline" width="300" height="100"> <g transform="translate(10,10)" class="container" width="280" height="96"> <rect x ...

The presence of Firefox Marionette has been identified by hCaptcha

Whenever I go on indeed.com using the firefox web driver in Marionette mode, I keep encountering an hCaptcha popup. In an attempt to avoid this, I experimented with a user script that alters the navigator.webdriver getter to return false right at the sta ...

One efficient way to handle multiple concurrent tasks in NodeJs is by using the forEach method to iterate

Having trouble getting the promises to return any values, as they are coming back empty. Despite following suggestions on Stack Overflow, I am still unable to resolve this issue. Frustration levels are high and I'm feeling lost; Can anyone help me pi ...

AngularJS: Understanding the difference between ng-show and using display:none

I recently encountered a scenario where I needed to hide an HTML element by default using CSS. Here's how I did it: HTML: <div class="box"> </div> CSS: .box { display: none; } However, I wanted to be able to show and hide the elem ...

Challenge encountered when attempting to detect multiple submit buttons using jQuery

I am currently attempting to identify which of the four submit buttons was clicked using jQuery 1.7.2. When any one of three specific buttons is clicked, I want an alert box to appear displaying the value of that particular button. Below is the HTML code s ...

Basic Ajax script fails to function properly

I'm having trouble with the external website that is supposed to output valid JSON data. The code seems too simple for there to be an issue, I've tried using both get and post methods. $(document).ready(function() { $.get("https://www.w3scho ...