Tips for accessing a new variable within an array of objects using JavaScript

How can I retrieve a new variable (section) after every 3 objects are called from an array in JavaScript ES6 Map? I've attempted to do this with an ES6 Map, but I'm not achieving the desired result. Can someone please assist me? Thank you! Below is my code:

const array = [
{
 id:1,
 name:'naren'
},
{
 id:2,
 name:'naren2'
},
{
 id:3,
 name:'naren3'
},
{
 id:4,
 name:'naren4'
},
{
 id:5,
 name:'naren5'
},
{
 id:6,
 name:'naren6'
},
{
 id:7,
 name:'naren7'
}
{
 id:8,
 name:'naren8'
}
]

//New Section
const section = 'New section';

Expected Output Result in console

Output:

naren1
naren2
naren3
New Section
naren4
naren5
naren6
naren7
naren8

Answer №1

To achieve the desired result, simply iterate through the array and verify each index accordingly.

array.forEach((element, idx) => {
  if (idx === 3) {
    console.log(`${element.name}\n${section}`);
  } else {
    console.log(element.name);
  }
});

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

PHP move_uploaded_file() function encountering an issue

As a newcomer to PHP, I am exploring the move_uploaded_file() function. I initiate an HTTP POST request from JavaScript/jQuery to a PHP file hosted on a Microsoft Azure server. The request includes an audio blob like so... mediaRecorder.ondataavailab ...

Retrieve an item fetched from the database using Javascript in MVC4 framework

How can I access the properties of an object returned from a database using JavaScript? This JavaScript function is invoked: function searchUser() { var userName = document.getElementById('UserName').value $.post("SearchForUser", { user ...

Utilizing dynamic jQuery events with variable integration

I'm having some trouble incorporating a variable into a dynamically added jQuery event. Every time I click, the message displayed is "The number is 3" for all div elements. $( document ).ready(function() { for (var i = 0; i < 3; i++) { ...

Is it possible to extract data from a table by adjusting Javascript in the inspector tool? The page is only showing today's data, but I'm interested in retrieving historical data by going back

My Desired Action: I am interested in extracting data from the 2nd and 3rd tables on this page. However, the data displayed is specific to the current 'day'. I wish to access readings from September 1st and import them into a Google Sheet. Speci ...

What is the best way to remove empty elements from an Array?

Having an issue with my API post request. If no values are entered in the pricing form fields, I want to send an empty array. I attempted to use the filter method to achieve this but it still sends an array with an empty object (i.e. [{}]) when making the ...

AngularJS - let's make pagination more interactive by adding an active class to the current page

Check out this fiddle I created: http://jsfiddle.net/tbuchanan/eqtxLkbg/4/ Everything is working as intended, but I'm looking to add an active class to the current page when navigating through the pages: <ul class="pagination-controle pagination" ...

Multiple button clicks causing events to fire repeatedly

My PHP file echoes a button, but when I click it, the action fires multiple times. Why is it behaving like this? I have tried solutions from Stack Overflow, but none of them seem to work. Any suggestions or corrections? $(document).on('click',& ...

Scrolling seamlessly on websites with a single page

I am developing a single-page website that uses different section IDs instead of multiple pages. It's functioning properly, but I want to implement smooth scrolling to the sections rather than just statically jumping to them on the page. Jsfiddle: ht ...

ESLint error caught off guard by function expression in customized MUI Snackbar Component with Alert

Struggling to create a personalized MUI Snackbar using the MUI Alert example from the official Documentation, but facing ESlint errors: error Unexpected function expression prefer-arrow-callback error Prop spreading is forbidden react/jsx-props-no-s ...

Vercel deployment issue: Hidden input values not being detected as expected

Whenever I attempt to update the data on Vercel, an error message is displayed: invalid input syntax for type uuid: "undefined" - unable to save Oddly enough, the data updates successfully when done locally. This is how I submit the form: <form onSu ...

End the response after sending with res.send() within the module

I am in the process of developing a module for validating requests that come through req.body. Instead of repeating the same code snippet in every server request, I aim to consolidate it into a single line within a module. const errors = validationResult( ...

What distinguishes v-text from v-load in Vue.js when concealing {{ Mustache }}?

When experiencing the "flash of uncompiled content" in Vue, the brief moment when the page is loading and you see the {{ Mustache }} syntax, developers often use either v-text or v-cloak. According to the documentation, v-text: Updates the element’s t ...

What are the steps to retrieve information from your personal server using Astro?

I have successfully set up a NodeJS server using Express and Astro for the frontend, with SSR configured through the Astro adapter for NodeJS. My current challenge is fetching data from the backend, and I am unsure of the correct approach to do so. Below ...

inject the HTML content into the <div> container

Snippet: https://jsfiddle.net/x9ghz1ko/ (Includes notes.) In my HTML file, there are two distinct sections: <section class="desktop_only"> and <section class="mobile_only">. The challenge lies in positioning a JavaScript sc ...

issues arising with React and the "this" keyword persist even after implementing binding

[UPDATE] I've encountered an issue where, in ListItem.js, when attempting to console log this.props (with or without passing props to the constructor), all props aside from the method are displayed. Even after removing the entire onchange event from L ...

Unresponsive JavaScript on specific element IDs

I'm experimenting with making three lines perform different animations: line 1 rotating 45deg and translating, line 2 becoming opaque, and line 3 rotating -45deg and translating. Check out my JS Fiddle here <a href="#"><div id="menu" onclic ...

Working with Java to parse non-strict JSON data that does not have keys enclosed in quotes

I am currently facing the challenge of parsing a string in JSON format where keys are not enclosed in quotes. While I have successfully parsed this string in Javascript, I am struggling to find a Java API that can assist me with parsing. The APIs I have at ...

To reveal the secret map location, just tap on the button - but remember, this only applies to

I am encountering an issue with duplicating a card and toggling the hidden location map. Currently, the location button only works for the first card and not for the rest. I need each card to independently open and hide the location map when clicked on the ...

Exchange data using socket.io in nodejs and express with a different javascript file

Imagine having a JavaScript file that needs to interact with another JavaScript file in order to share data between them. For instance, let's consider a file named game_server.js. Within this file, there are two variables that we want to access in th ...

Having an issue with retrieving value from a textfield in JavaScript

<input id="checkOldPassword" type="button" title="Check New Password" value="Check New Password" onclick="checkPassword()" /> <input id="newPassword" type="text" maxlength="8" min="8" /> <script language="javascript"> function checkPassw ...