Unexpected outcome when returning a map

Encountered a puzzling issue that requires immediate clarification. When I input the following code into my project:

this.metadata = json.metadata.map((x) => {return new Metadatum(x);});
console.log(this.metadata[0].value);

The output consistently shows 'undefined' for every element in json.metadata.

However, when I switch gears and use the map function incorrectly (I acknowledge that using forEach would be more appropriate), like so:

json.metadata.map(x => this.metadata.push(new Metadatum(x)));
console.log(this.metadata[0].value);

Suddenly, the correct values are displayed instead of undefined.

I am left puzzled as to why assigning to this.metadata (which is an array of Metadatum objects) results in undefined.

Answer №1

Make sure to review your data structure; the .map function takes an array and then creates a new one based on it. Check out this example:

var keyValueArray = [
    {name:'Alice', score:90},
    {name:'Bob', score:80}, 
    {name:'Charlie', score: 70}
];

var transformedArray = keyValueArray.map(function(item){ 
    var newItem = {};
    newItem[item.name] = item.score;
    return newItem;
});

Answer №2

If you want to utilize the .map method, there are several options available:

var data = [1, 2,3,4,5,6,7];
function Metadatum (x) {
  this.value = x;
}

let metadata = data.map((x) => { return new Metadatum(x); });
let metadata1 = data.map(x => new Metadatum(x));
console.log(metadata[0].value);
console.log(metadata1[0].value);

Here are some examples of ES6 arrow function syntax:

(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
     // equivalent to:  => { return expression; }

// Parentheses are optional when there's only one parameter:
(singleParam) => { statements }

singleParam => { statements }

// A function with no parameters requires parentheses:
() => { statements }

To learn more about arrow functions and their syntax in detail, you can visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

EDIT: To see a working example, check out this JSBin link: https://jsbin.com/huzuyo/1/edit?html,js,console

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

Adding a condition to the react-router v6 element: A step-by-step guide

I am currently in the process of updating my project from v5 to v6 of react-router-dom. However, I have encountered an issue. Everything was working fine in v5 <Route path={`${url}/phases/:phaseIndex`}> {(chosenPhase?.type === PhaseTy ...

Navigate to the previous or next page using JavaScript

I've been struggling to figure out how to navigate one page up and down using simple links, but I haven't found a solution that works for me. The URL I am working with is: . When the "next page" button is clicked, it should go to ?page=2, and whe ...

Guide to executing Jest tests with code coverage for a single file

Instead of seeing coverage reports for all files in the application, I only want to focus on one file that I am currently working on. The overwhelming nature of sifting through a full table of coverage for every file makes it difficult to pinpoint the spe ...

Dealing with ASP.NET forms that involve a javascript plugin generating substitute input

I'm facing an issue with my ASP.NET MVC webpage where I submit a form using AJAX in the following way: function ValidateFormAndAjaxSubmit(formId, callingElement) { if (IsNotDblClick(callingElement.id)) { var _form = $("#" + formId); ...

Is there a quicker method than using document.getElementById('element-id').innerHTML to retrieve content?

Currently, I am developing a user-friendly step-by-step wizard for my website to gather information about custom orders. Utilizing JavaScript, I have been tasked with updating the content of each "page" using the document.getElementById('element-id&ap ...

Transforming the format from YYYYMMDD using MomentJS

Currently, I have a date in the format of YY as shown here: 20141229. I am attempting to convert it into Timestamp format. I attempted using moment(date).format('x'), but received an "Invalid date" error. I'm unsure of how to accomplish this ...

ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I att ...

Struggling to uncheck all selected boxes using jQuery

I've attempted various methods, but I'm unable to create code that will uncheck or clear all checkboxes once they have all been selected. Here is the latest version of my code... $(".select_all").click(function(){ var state = ($(this).html( ...

An introduction to utilizing .keypress() in jquery

I'm exploring the use of .keypress() to allow users to press enter and trigger a button click on my modal (which closes the modal). When I initially code it as: $(document).keypress(function () { console.log('keypress'); }); it works, but ...

Guide to creating unit tests for document.URL in Angular 5 specifications

Currently attempting to simulate document.URL = 'dashboard'; however, encountering an issue where it states that I can't assign to url because its readonly property. This problem arose while writing jasmine test cases click here for image de ...

Making rapid formatting changes by rearranging the positioning of words in Javascript

Struggling to untangle my complex code, I'm unable to make the necessary adjustments. Here's what I have: var stocks= [ ["Beef (80/20) raw","oz",115.4451262,3.293742347,72,"4.85 gallons","5.65 pounds","0 - ",2.142,19,20,"0.0001275510204"," ...

How to Utilize Muuri Javascript Library with Bootstrap Tabs: Resizing Required for Expansion?

Struggling for days and feeling frustrated, I'm hoping someone can help me crack this mystery. My idea is straightforward - three Bootstrap 4 tabs with drag and drop functionality inside each, all displayed in a responsive stacked masonry layout. To a ...

Issues encountered when rendering textures from a canvas in Three.js

I've been working on creating a texture from a canvas. I managed to successfully render a blank canvas, but encountered issues when trying to draw an image on the canvas and then render it. This is the code snippet I am currently using: var canva ...

I am having trouble with the browser detection not accurately identifying the browser I am currently using

Currently, I am working on a JavaScript code that will simply display the name of the browser being used to view the web page. Despite me using Safari, none of the navigators seem to recognize it as the current browser. The information displayed in my brow ...

By utilizing a combination of JavaScript and jQuery, we can dynamically fill interconnected select boxes with data from an

After finding solutions to this particular query, I successfully managed to populate a select box based on the selection made in another select box. (You can see my answer here) This was achieved by retrieving data from an array structure that was generate ...

Exploring the benefits of integrating ES6 modules in Express server technology

Is it possible to utilize ES6 modules in my Express application without relying on babel or @std/esm? find an alternative method that doesn't involve transpiling or using esm? Once I have started working on app.js in Express, it seems challenging to ...

Exploring the capabilities of SVG and audio integration in web browsers

I am curious if it's possible to incorporate audio into an SVG file in a web browser. I came across this thread here, but unfortunately, I can't leave a comment =/ I tried implementing the code from this website, but it doesn't seem to work ...

Adjust the initial slider according to the values displayed in the following four sliders

Having an issue updating the slider value in the first one based on selected values from four other sliders. The selected value should not exceed 50, which is the maximum value in the first slider. Link to Working Fiddle : Below is the HTML code : & ...

Do back-end routes get activated when the route path in the URL matches, or when a fetch request is initiated from the front-end?

Exploring the contrast between utilizing a fetch API versus directly visiting the URL corresponding to the route path. Consider a backend route structured as follows: let ALL_RESTAURANTS = [ { id: "0b65fe74-03a9-4b37-ab09-1c8d23189273", name: ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...