Try implementing an alternative to using flatMap in JavaScript

Looking for an alternative method to achieve the same functionality as flatmap in JavaScript with lower ES5 version for the following mapping.

const b = [{
  "errorname": [{
    "name": "Error 01",
    "desc_1": "Test: 01",
    "desc_2": "Testing"
  }, {
    "name": "Error 03",
    "desc_1": "Test: 03",
    "desc_2": "Testing"
  }],
}, {
  "errorname": [{
    "name": "Error 02",
    "desc_1": "Test: 02",
    "desc_2": "Testing"
  }, {
    "name": "Error 09",
    "desc_1": "Test: 09",
    "desc_2": "Testing"
  } ]
}];

var errorMap = generateErrorMap(b);

function generateErrorMap(arr){
  var newArray = [];
  arr.forEach(function(elem){
    elem.errorname.forEach(function(error){
      var tempObj = {};
      tempObj[error.name] = {desc_1: error.desc_1, desc_2: error.desc_2};
      newArray.push(tempObj);
    });
  });
  
  return newArray;
}

console.log(errorMap)
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Exploring options for ES5 compatibility with similar operations. The application is accessed using an electron app that does not support ES9.

Answer №1

If you need to use the flatMap function in your code, there are a couple of options available to you. You can either download a polyfill or create your own implementation. Here is an example of how you could implement it:

Array.prototype.flatMap = function(mapper) {
  var result = [];

  for (var i = 0; i < this.length; ++i) {
    var item = mapper(this[i], i, this);

    if (!Array.isArray(item)) {
      item = [item];
    }

    for (var j = 0; j < item.length; ++j) {
      result.push(item[j]);
    }
  }

  return result;
}

Once you have implemented this, you will be able to call myArray.flatMap just like you would with any other array method.

Answer №2

To implement an inner-outer reduce, you can nest the calls within each other. This approach is suitable for ECMAScript versions before 5/6.

const b = [{
  "errorname": [
    { "name": "Error 01", "desc_1": "Test: 01", "desc_2": "Testing" },
    { "name": "Error 03", "desc_1": "Test: 03", "desc_2": "Testing" }],
}, {
  "errorname": [
    { "name": "Error 02", "desc_1": "Test: 02", "desc_2": "Testing" },
    { "name": "Error 09", "desc_1": "Test: 09", "desc_2": "Testing" }
  ]
}];

var errorMap = b.reduce(function(outer, group) {
  return group.errorname.reduce(function(inner, item) {
    return inner.set(item.name, {
      desc_1: item.desc_1,
      desc_2: item.desc_2
    });
  }, outer);
}, new Map);

console.log(Object.fromEntries([...errorMap]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Interactive Google Maps using Autocomplete Search Bar

How can I create a dynamic Google map based on Autocomplete Input? Here is the code that I have written: <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeAtURNzEX26_mLTUlFXYEWW11ZdlYECM&libraries=places&language=en"></scri ...

Ways to activate a file selection dialog box using JavaScript?

Is it possible to implement an "open file dialogue" box using JavaScript? ...

Having difficulties accessing the git repository through the application

I am currently working on a Node.js application that needs to connect to a Git repository via the app. The connection works fine locally, and it also runs smoothly when I docker build and run it within a container on my local machine. However, upon deplo ...

What could be the reason for my SQL query functioning correctly in my editor, but not in my JavaScript function?

When I run my SQL statement in my SQL editor, it works perfectly fine. However, when I try to use it in my JavaScript function, I get an error saying there is an invalid column for my client ID. function getFeedposts(data) { var limit = data.dollarLimit; ...

What is the best way to handle and fix incorrect characters?

I have a JavaScript code snippet that is designed to check for invalid characters in a string. The only allowed characters are a-z, A-Z, 0-9, and -: var str = 'Some string!', invalid_characters = []; if (/^[a-zA-Z0-9-]*$/.test(str) == false ...

Tips for resolving the never-ending buffer issue during the checkout process on WooCommerce for WordPress

Currently facing a persistent issue with the Woocommerce checkout page where the order review section is continuously buffering and not loading as intended. Despite extensive research and attempts to troubleshoot, no resolution has been found yet. https:/ ...

Exploring the Canvas with Full Element Panning, Minimap Included

Currently, I am working on incorporating a mini map onto my canvas that mirrors what is displayed on the main canvas. The main canvas includes zoom and pan functions. I have created a rectangular shape for the minimap to display the content of the canvas. ...

Issue encountered when comparing parameters in Express (GET request) and ultimately not meeting the required condition

I am currently working with Express 3.0 and encountering an issue while trying to compare values in the database based on certain IDs. Here is the code snippet that I can't seem to get functioning correctly: function(req, res) { var Parking = mongoo ...

Interacting with a Hapi JS API through a distinct Vue JS Frontend. The data in request.payload is not defined

As I take my first steps on Hapi JS, I am facing the challenge of connecting my app to a SQL Server DB. My current task involves sending login data from a Vue CLI JS frontend to a Hapi JS Api using axios. The login process essentially consists of a "SELEC ...

Cross-Origin Request Blocked despite having specified headers

I am encountering a CORS error while attempting to make a get request from my Vue application. My Node.js Express server is set up with a local Mysql database, and I have configured the necessary headers to allow access from my Vue app running on localhost ...

Exploring image retrieval documents in PhoneGap

In the process of developing a PhoneGap application that involves capturing images using the camera and subsequently uploading them, I have encountered an issue. In PhoneGap, there are two modes for camera operation: raw base64-encoded data or a file URI. ...

Ways to prompt the debugger to pause whenever a specific script file is called during execution in Edge/Chrome debugger

I am currently in the process of debugging a Typescript web application, which is quite new to me as I have never delved into web development before. This particular project entails multiple script files and various libraries. While running the applicatio ...

Tapping on the Child Component will automatically close the currently opened list

Recently, I created a menu that expands to show all child elements when clicking on the parent menu link. However, I encountered an issue where clicking on a child element collapses the menu. You can view a demo of my implementation here: http://codepen. ...

What is the best way to determine if a value stored in localStorage is present in an

After reading this particular response, I learned that I should utilize $.inArray. Following this advice, my code looks like this: var curPostId = $(".my_post_id").attr("data-id"); if($.inArray(curPostId, lines)) { $('#'+localStorage.getItem( ...

Utilizing the request module in Node.js with ExpressJS

Currently, I am in the process of creating a helper method within my code that will handle user authorization. This function, named "usePermissions", is being developed following the React approach but for backend functionality. Upon implementa ...

What is the process for integrating ng-bootstrap into an Angular 5 project?

Has anyone encountered issues loading ng-bootstrap in their Angular project? I'm experiencing difficulties and would appreciate any insights. Thank you for your help! This is my app.module.ts file: import { BrowserModule } from '@angular/platf ...

Refreshing pane content within Kendo UI Splitview

I am utilizing the Kendo UI splitview. In my setup, I have configured one pane on the left for navigation and another pane on the right for content display. The left pane contains 4 navigation links structured as follows: <div data-role="pane" id="si ...

What is the most effective method for incorporating web APIs (such as setTimeout, fetch, etc.) within the V8 engine?

Currently, I am tackling a project that requires the use of v8 in Go for running JS code. To achieve this, I am utilizing the v8Go library. The challenge I am facing is the inability to utilize functionalities like fetch, setTimeout, and other Web APIs. Wh ...

Issue encountered while initializing session_start() in PHP REACTJS AXIOS

https://i.sstatic.net/bSelX.pngWhen attempting to log in to my web application, I encountered an issue where the session is not opening after entering the correct email and password. Strangely, there is no PHPSESSID present in the console > application. ...

iOS does not support webkit-transform functionality

I've been working on incorporating a navigation drawer into my Sencha Touch app by following this article. The animation mentioned in the article utilizes webkit-transform, which functions perfectly on Chrome and Android devices, but seems to be causi ...