Adjust index starting from 0 in JavaScript

Struggling with setting a consistently unique index that increments by one.

Here is an example of my array:

const originalArr = [
  {
    name: 'first parent array',
    childArray: [
      {
        name: '1 / first child'
      },
      {
        name: '1 / second child'
      }
    ]
  },
    {
    name: 'second parent array',
    childArray: [
      {
        name: '2 / first child array'
      },
      {
        name: '2 / second child array'
      }
    ]
  }
]

The desired output should look like this:

const expectedOutput = [
  {
    name: 'first parent array',
    additionalInfo: [
      {
        index: 0,
        name: '1 - first child'
      },
      {
        index: 1,
        name: '1 - second child'
      }
    ]
  },
   {
    name: 'second parent array',
    additionalInfo: [
      {
        index: 2,
        name: '2 - first child array'
      },
      {
        index: 3,
        name: '2 - second child array'
      }
    ]
  }
]

I need each item in additionalInfo to have a unique index starting from 0.

My attempt so far has resulted in incorrect index numbers:

return originalArr.map((parent) => {
    return {
      name: parent.name,
      additionalData: parent.childArray.map((child, index) => ({
        name: child.name,
        index: index   // Struggling to increment properly here
      })),
    };
  });

Answer №1

To handle the index of children separately from the loop, you can try implementing this approach:

let i = 0;

return parentArr.map((parent) => {
  return {
    name: parent.name,
    additionalData: parent.childArray.map((child) => ({
      name: child.name,
      index: i++
    })),
  };
});

Answer №2

It is important to keep the index count separate from the map function to ensure it does not reset on each iteration.

This functionality can be encapsulated in a reusable method as illustrated below.

const parentArr = [
  {
    name: 'first parent array',
    childArray: [
      {
        name: '1 / first child'
      },
      {
        name: '1 / second child'
      }
    ]
  },
    {
    name: 'second parent array',
    childArray: [
      {
        name: '2 / first child array'
      },
      {
        name: '2 / second child array'
      }
    ]
  }
];


const transformArray = root => {
  let i = 0;
  return root.map(({ name, childArray }) => ({
    name,
    additionalData: childArray.map(({ name }) => ({
      index: i++,
      name
    }))
  }));
};

console.log(transformArray(parentArr));

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

Can you explain the process of initiating a script?

Seeking Answers: 1) When it comes to initializing a script, is there specific code placement in the js file or do you need to create initialization code from scratch? 2) What sets jQuery apart from other scripts that require activation - why does jQuery. ...

JavaScript: Implementing a for loop to dynamically adjust CSS properties

How can I adjust the margin-top property of the ball element when clicking a button? Below is my current code, but it's not working as expected. Can you help? let ballMargin = ball.style.marginTop; moveButton.addEventListener('click', funct ...

Leverage variables in JavaScript to establish a unique style

function AdjustScale(){ scaleX = window.innerWidth / 1024; scaleY = window.innerHeight / 768; element = document.getElementById("IFM"); element.style.transform = "scale(" + scaleX + ", " + scaleY + ")"; } I'm facing an issue with thi ...

What is the process for obtaining a new token in a Linnworks embedded application?

I decided to share my issue on this platform since the support from Linnworks is virtually non-existent. My dilemma involves a private embedded app created within Linnworks that showcases orders in spreadsheet format. The app, constructed using Vue.js and ...

What potential issues can arise when importing a default export alongside a named export and using webpack in conjunction with babel?

I have two distinct constructors in my codebase: SignUp and GoogleSignIn. They are structured as follows: import SignUp, {gapi_promise} from "./SignUp"; /** * * @param element * @extends SignUp * @constructor */ function GoogleSignIn(element){ SignUp ...

Navigating between interfaces without the need to constantly refresh or reload

Currently, I am in the process of developing a website using ASP.NET MVC that allows users to navigate between pages without refreshing each time. My approach involves treating views as 'areas' or mini master pages, utilizing partial views inste ...

What is the best way to add the current date to a database?

code: <?php session_start(); if(isset($_POST['enq'])) { extract($_POST); $query = mysqli_query($link, "SELECT * FROM enquires2 WHERE email = '".$email. "'"); if(mysqli_num_rows($query) > 0) { echo '<script&g ...

If the width of the table is set to 100% in the CSS, the legend in the Flot chart will automatically shift to the

When the CSS for the table is set to { width:100%}, the Flot chart's legend moves to the left side. Is there any way to maintain the table { width:100%} while also preventing this shift, considering that the CSS is applied site-wide? Here is a jsfid ...

Importing JavaScript files to work with Vue-Router: A Step-by-Step Guide

Seeking guidance on importing JavaScript files correctly throughout my Vue project, including within the components used to implement changes with Vue-Router. Currently, encountering an issue where I must reload the component in order for the JavaScript to ...

Struggling to vertically align elements within iron-pages

Struggling to vertically center the content within iron-pages (nested in a paper-drawer-panel). Check out the code snippet below: <paper-drawer-panel id="drawerPanel" responsive-width="1280px"> <div class="nav" drawer> <!-- Nav Conte ...

Every attempt to connect with the webservice via an ajax call has ended in failure

I am encountering an issue with a webservice call that I am making using jQuery's AJAX method. Despite receiving JSON data from the webservice when accessed directly through the browser, my site always triggers the error function rather than the succe ...

what is the best way to make a dynamic array in C++?

Looking for some advice on how to tackle this problem with a function I'm working on: void reverse(int* nums, unsigned int size) The objective of this function is to reverse the values within the array passed into it. My initial approach was to cre ...

javascript monitoring numerous socket channels for echoes

Currently, I am in the process of developing a chat application. On the server side, I am utilizing: php, laravel 5.4, and pusher. On the client side, I have incorporated vue.js along with laravel-echo. Initially, I successfully created a "public chat roo ...

Having difficulty with horizontal frequency bar chart

Struggling with coding in C and encountering numerous issues. I apologize for any errors in my code. I am attempting to create a simple horizontal histogram that displays the frequency of integers in an array. However, no matter what I try, it always print ...

Ways to trigger an npm script from a higher-level directory?

After separately creating an express-based backend (in folder A) and a react-based front-end project (in folder B), I decided to merge them, placing the front-end project inside the back-end project for several advantages: No longer do I need to manu ...

Having trouble setting the state of an array using NextJS useState?

I'm facing an issue where the array saved to a useState state is not updating properly. Despite properly returning values for the variable first, the variable "data" remains an empty array. Interestingly, adding a console.log("restart") statement und ...

Move the cursor to the bottom of a div that can be edited

I have been struggling to position the cursor at the end of the next or previous editable content tag if the current one is empty. However, when I try to set focus, it always ends up at the beginning of the text instead of the end. I've tried various ...

Generate a dot density map with the help of Google Maps

I am looking to create a dot density map using Google Maps for my state. I have all the counties outlined with their respective populations, and I want to scatter dots randomly within each county to represent the population. The goal is to make a dot densi ...

Firefox users may notice that the pop-up video player appears in unusual locations on their screen

I'm encountering an issue with a pop-up video player that is triggered by an "onClick" event in HTML elements. The problem arises when there are multiple video players on the same page - in Firefox, the first video loads at the bottom of the page, req ...

What could be causing my AngularJS JSONP request to fail when trying to query Solr?

After attempting to query my Solr server with the provided code snippet: var url ="http://localhost:8080/solr/sdc/selectwt=json&callback=JSON_CALLBACK&q=opioid" $http.jsonp(url ).success(function(res){ console.log(res) }) An error is returned ...