Guide on utilizing the reduce method with objects

I am attempting to use the reduce method on an object to create an HTML list

const dropdownTemplate = (data) => {
console.log(data); // no data displayed
return `
<li class="dropdown__item" data-value="${data.value}"><span class="dropdown__itemCode">${data.code}</span> <span class="dropdown__itemText">${data.name}</span></li>
`;
};

const data_obj = JSON.parse('[ { "type": "hotel", "value": 25, "name":"Hotel name", "code": "sn", "lat" : "1.3", "long" : "1.33" } ]');
const fetched_items = data_obj.reduce((item, generated) => {
generated += dropdownTemplate(item);
return generated;
}, '');
console.log(fetched_items); // always contains undefined values

However, I can't figure out why the item is always empty (resulting in a list with undefined values).

What mistake am I making here?

Answer №1

In my opinion, you have mixed up the usage of item and generated.

generated actually refers to the element that is retained from one iteration to the next loop, while item pertains to the element in the array that is being processed in the current loop.

const dataObj = JSON.parse('[ { "value": 25, "name":"Hotel name", "code": "sn"  }, { "value": 30, "name2":"Hotel name2", "code": "sn2" } ]');

const dropdownTemplate = data => `<li class="dropdown__item" data-value="${data.value}"><span class="dropdown__itemCode">${data.code}</span> <span class="dropdown__itemText">${data.name}</span></li>\n\n`;

const fetchedItems = dataObj.reduce((tmp, x) => `${tmp}${dropdownTemplate(x)}`, '');

console.log(fetchedItems);

Answer №2

For optimal performance in this type of situation, it is recommended to utilize a map function.

The structure for reduce params looks like this: (aggregate, item) => {}

const dropdownTemplate = (data) => {
return `
    <li class="dropdown__item" data-value="${data.value}">
    <span class="dropdown__itemCode">${data.code}</span> <span class="dropdown__itemText">${data.name}</span>
    </li>`;
 };

const data_obj = JSON.parse('[ { "type": "hotel", "value": 25, "name":"Hotel 
name", "code": "sn", "lat" : "1.3", "long" : "1.33" } ]');

const fetched_items = data_obj.reduce((combinedHtml, item) => {
   combinedHtml += dropdownTemplate(item);
   return combinedHtml;
}, '');

console.log(fetched_items);

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 React Apexchart fails to correctly adjust its height based on its parent container when set to 100%

Currently, I am working with react-apexcharts and facing an issue where I am trying to set the height of the chart to be 100% of its parent element. However, instead of taking the height from its parent, it is only showing a minimum height of 445px. Even a ...

After refreshing in FireFox, the "disabled" attribute of the button fails to function

On my webpage, there are 2 buttons - one enabled by default and the other disabled. When I click on an enabled button, their states switch - the enabled button becomes disabled and vice versa. This functionality works perfectly in Chrome, Edge, and IE11, b ...

What steps can I take to ensure that my Onetrust consent script is properly loaded before implementing Facebook pixel tracking in NextJS?

Looking for a solution to load my Cookies consent script as the first script in our NextJS application. The problem arises because we have Facebook pixel tracking implemented and they use parentNode.insertBefore which places their script on top. This is h ...

Having trouble executing javascript with Ext.Ajax in Sencha-Touch2?

Currently, I am utilizing htmlPanel.js in Sencha-Touch as discussed in the Forum here to exhibit local HTML content. Even though I can load the HTML content with standard HTML tags, I'm facing issues with loading JavaScript. Here's the snippet o ...

Tips for stopping links in iOS web applications from launching in a new Safari tab

I am in the process of developing an HTML application specifically for iPads. To enhance user experience, I have added the web app to the homescreen using the "favorite" option. However, I encountered an issue where every internal URL opens in a new Safari ...

Easily visualize the JSON object hierarchy within Eclipse using JavaScript

Is there a way to view the JSON parse objects structure in Eclipse without using console.log() in Chrome due to cross domain issues? I need assistance with how to view the [object Object] returned structure from Json.Parse. ...

Is it possible to eliminate the default placeholder text from Safari browser?

My goal is to design a form that includes date and time input fields. The placeholder text should move up by X pixels when the user clicks on the field. While the form appears fine in Chrome, there seems to be an issue with overlapping form fields in Safa ...

Maximizing efficiency in processing multiple requests simultaneously using ajaxSetup's data

I need to enhance an existing ajax request within our CMS by adding additional data. Specifically, I am working with a media library that loads image data (json), and I want to incorporate more images from an external source. var promise_waiting = []; jQu ...

Adjust the size of an element using the jQuery library's knob.js

There is a page Once the button is pressed, a circle element from the library jquery.knob.js appears. I am trying to change the size of the circle and have written this code: <div style="float:left; width:255px; height:155px"> <input ...

Ways to refine date results using JavaScript

Here is the JavaScript code I have: $(".datepicker").datepicker(); $(".datepicker-to").datepicker({ changeMonth: true, changeYear: true, maxDate: "0D" }); This code ensures that the date selected cannot be beyond the cur ...

The Angular MatStepper is unable to detect saved values from two string arrays, although it is able to detect values from a different string array

In my application, there is a MatStepper component that facilitates navigation through the signup flow. A method exists to load cached values when available, causing the MatStepper to skip to Page 2. Subsequently, another method pre-fills the form with the ...

Is it possible to arrange a react map based on the length of strings?

I am working on a React function that loops through an object and creates buttons with text strings retrieved from the map. I want to display the text strings in order of their length. Below is the code snippet for the function that generates the buttons: ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...

Ensure the item chosen is displayed on a single line, not two

I've encountered an issue with my select menu. When I click on it, the options are displayed in a single line. However, upon selecting an item, it appears on two lines - one for the text and another for the icon. How can I ensure that the selection re ...

Troubleshooting issue with multer code failing to save files in designated directory within nodejs server when using reactjs frontend

I'm facing an issue while trying to upload a photo into my server folder. Even though the submission process adds the picture to my database, it does not display the image in my server folder. The frontend of my application is built using React JS, an ...

In what way does ReactJS enable me to utilize constant functions before they are declared?

I'm intrigued by the concept of using a value before defining it in ReactJS. Let's explore this through an example: function CounterApp() { const [counter, setCounter] = useState(0); const increaseValueTwice = () => { increaseValue() ...

default radio option with pre-selected value

Below is a radio option list, but I'm having trouble getting the desired default selection on first render: <label class="radio normalFontWeight"> <input type="radio" name="Criteria" data-ng-value="EVERYONE_REVIEWED" data-ng- ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

Apollo-Server presents errors in a polished manner

It seems like the question explains itself adequately. I am currently using 'apollo-server-core' version 3.6.5 Desired Errors: { "errors": [ { "message": "Syntax Error: Unexpected < ...

HTML - implementing a login system without the use of PHP

While I am aware that the answer may lean towards being negative, I am currently in the process of developing a series of web pages for an IST assignment in Year 9. Unfortunately, the web page cannot be hosted and our assessor lacks the expertise to utiliz ...