Employing the map() function or a similar method to transform the array data into the specified format

Today, I decided to have some fun with the map() function in JavaScript. I am working with an array and trying to return the data from the pages property. However, I want the page id to serve as the key, and the index of that page within the pages array to be the value. Can someone help me find out what mistake I'm making?

let result = [
  {
      "id": 10000089,
      "units": [
          {
              "id": 10000200,
              "pages": [
                  {
                      "id": 100000882
                  }
              ]
          },
          {
              "id": 10000340,
              "pages": [
                  {
                      "id": 100000912
                  },
                  {
                      "id": 100000915
                  },
                  {
                      "id": 100000919
                  }
              ]
          }
      ],
  }
];
// Here is my attempt, but it doesn't give the desired output format below
result.flatMap(el => el.units.map((e, i) => (e.pages)));

Desired Output:

pages = [
  100000882 => 0,
  100000912 => 0,
  100000915 => 1,
  100000919 => 2,
]

If you'd like to check out the code on Stackblitz, click this link: https://stackblitz.com/edit/js-mc9rqe

Answer №1

To get the desired output, you should return an object instead of an array. Utilize methods like Array.prototype.flatMap or Object.fromEntries to achieve this transformation.

let result=[{id:10000089,units:[{id:10000200,pages:[{id:100000882}]},{id:10000340,pages:[{id:100000912},{id:100000915},{id:100000919}]}];

const pages = Object.fromEntries(
  result.flatMap(item => item.units.flatMap(unit => unit.pages.map((page,i) => ([page.id, i]))))
);
console.log(pages);

Keep in mind, that Object.fromEntries() expects an array containing arrays with a [key, value] pair structure, which will then be transformed into an object. In your scenario, the page.id serves as the key, while the index from the last map operation acts as the value.

Answer №2

Within your dataset, the element pages is structured as an array of objects. Therefore, it is necessary to iterate through each page individually.

  • Utilizing the Array.flat method

let result=[{id:10000089,units:[{id:10000200,pages:[{id:100000882}]},{id:10000340,pages:[{id:100000912},{id:100000915},{id:100000919}]}]];

const getFormattedData = data => {
  const res = data.map(datum => datum.units.map(unit => unit.pages.map(({ id }, i) => ({
    [id]: i
  }))));
  return res.flat(2);
}
console.log(getFormattedData(result));

  • Employing the Array.flatMap function

let result=[{id:10000089,units:[{id:10000200,pages:[{id:100000882}]},{id:10000340,pages:[{id:100000912},{id:100000915},{id:100000919}]}]];

const getFormattedData = data => {
  return data.flatMap(datum => datum.units.flatMap(unit => unit.pages.map(({ id }, i) => ({
    [id]: i
  })));
}
console.log(getFormattedData(result));

Please note that both methods mentioned above will yield an Array comprising of objects.

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

The webpage runs smoothly in the browser, but unfortunately displays a blank screen on mobile devices

I'm currently in the process of developing an app utilizing a combination of the Ionic Framework, Phonegap, and AngularJS. Within the app, I have a directive called Item. While this directive functions perfectly when testing the application on a brow ...

Fulfill the promise to retrieve the value contained within

Is there a way to use TypeScript to call the Wikipedia API for retrieving a random page title and save it in a variable for later use? I am struggling with resolving promises as I keep getting ZoneAwarePromise returned. I'm new to both promises and Ty ...

Transmit information across disparate components in Vue.js

This situation involves a Graph component displayed in the body of the page, allowing user modifications. Additionally, there is a Search component located in the header of the page. These two components are independent - Graph is exclusive to the body o ...

Display HTML content in autocomplete using jQuery UI

I implemented a search feature on my website using jQueryUI, similar to how it works on Facebook. Below is the jQuery code: //search main function split( val ) { return val.split( ); } function extractLast( term ) { return split( term ).pop(); } ...

Ways to send information to browser javascript from Spring MVC controller

Looking for the most efficient method to transfer data from Spring MVC to JavaScript. Let's say there is an array in JavaScript: var myArray = new Array(); And in the Java backend, there is another array: int[] myArray = new int[100]; What would ...

Challenges faced when subscribing to global events in JavaScript

I have some questions about the JavaScript code snippet below: What does .events.slice(-1)[0][0] signify? Similarly, could you explain the purpose of nodes_params += "&ns=" + GLOBAL_EVENT + "," + start_from + ",-,-";? Could you elaborate on what is m ...

There seems to be an issue with accessing the Angular module, even though it has been clearly

While attempting to execute the code below, two errors are encountered: Error: [$injector:nomod] Module 'rooms' is not available! The module name is spelled correctly and loaded dependencies have been included. The modules are structured in the c ...

Having trouble navigating the dependency graph: Unable to locate module './crypto_auth' in sodium-universal

Encountering the following error while trying to browserify a node project from https://github.com/datproject/sdk: Error: Can't walk dependency graph: Cannot find module './crypto_auth' from 'C:\myPath\node_modules\sodium ...

How can the Node app utilize an HTML page to reference another JavaScript file? Ran into an unexpected syntax error: `Uncaught SyntaxError: Unexpected token '<

I'm trying to figure out how to call another script from an HTML page that is being served by my node project's localhost server. Here's the basic setup: index.js var http = require('http'); var fileSystem = require('fs' ...

Issue: The component factory for GoogleCardLayout2 cannot be located

Recently I've been working on an Ionic 3 with Angular 6 template app where I encountered an issue while trying to redirect the user to another page upon click. The error message that keeps popping up is: Uncaught (in promise): Error: No component fac ...

Delay the execution in selenium webdriver using Java until the login button is clicked manually

Can Selenium Webdriver be used to pause code execution with webdriver.wait until the user clicks the login button on a form? The form includes a Captcha that requires manual input, preventing automated clicking of the button by the script. Clicking the log ...

Animate or resize with a focal point

Seeking suggestions on how to create an animation effect for changing the width and height of a div from the top center. I experimented with using effect('scale'), but it reverts back after completion due to being based on show/hide actions. I t ...

Response from Socket.io: What is the best way for the server to respond to all clients after receiving input from multiple clients?

Currently diving into the realm of node.js, express, and socket.io Thrilled to report that my server is up and running, successfully connecting to the browser via localhost:3000 Communication between client and server is seamless both ways. Now, onto th ...

w3schools example showcasing the power of AJAX

How can I run this example on my local machine? http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_httprequest_js (page no longer available) I want to access the XML file hosted on w3schools without moving it to my machine. Can I run the HTML and J ...

The issue of actions failing to flow from sagas to reducers in React.js

Upon user login, the success response is received but the action is not passed to the reducer. Strangely, during user registration, everything works smoothly. //saga.js import { put, takeEvery, all, call } from 'redux-saga/effects'; import {getRe ...

Tips for retaining form inputs without the need for a submit event when the page is reloaded or refreshed

I have a form on a page with multiple text inputs In addition to the form, I have implemented Zend pagination to allow users to select results. However, when using Zend paginate, the user's form inputs are lost because it is not submitted. Since th ...

Issue with passing incorrect props to child component occurs specifically on pages 2 and beyond within react-table

Implementing a button in each row of a table using react-table to trigger a react-modal is functioning correctly on the initial page. However, when navigating to subsequent pages, an issue arises where the incorrect id prop is being passed into the custom ...

Using Mongoose to perform an upsert operation into an array of objects while taking the maximum value for a specific key

I am faced with a complex upsert task in Mongoose that involves other updates as well. The structure of my model is as follows: const UserSchema = new Schema({ username: { type: String, index: true, unique: true }, email: String, password: { type: S ...

Tips for concealing a div in JavaScript when other divs are not present

Is there a way to hide the title div if related divs are not present in the HTML structure? This is the main HTML structure: <div class="row parent"> <div id="title-1" class='col-12 prov-title'> <h2 ...

Best way to create a 3D array in PHP

I am trying to structure an array in PHP that resembles the following format: _________________________________________ |time | event | childEvents | |_____|_______|__________________________| |9:00 |Event1 | String[]{subE11, subE12} | |_____ ...