JavaScript - undefined results when trying to map an array of objects

In the process of passing an object from a function containing an array named arrCombined, I encountered a challenge with converting strings into integers. The goal is to map and remove these strings from an object titled results so they can be converted into integers. However, I am currently facing an issue where I am getting undefined while mapping the array of objects for results.

Below is a sample of the array:


0: Object { result: "494,927", risk: "LOW", sector: "Online" }
1: Object { result: "48,883", risk: "MEDIUM-LOW", sector: "Retail Stores" }
2: Object { result: "59,976", risk: "MEDIUM-LOW", sector: "Store Pick up" }
3: Object { result: "1,205,915", risk: "MEDIUM", sector: "Drive in" }
4: Object { result: "1,434,262", risk: "LOW", sector: "In store" }

To resolve this issue, I declared a variable called finalResult within my mapping function to target the "result" value as follows:


let finalResult = arrCombined.arrCombined.result.map(function (e) {
  return Number(e.replace(/(,\s*)+/g, '').trim());
});

console.log(finalResult); // undefined.

The expected outcome is for finalResult to return the result objects as numbers, such as

494927, 48883, 59976, 1205915, 1434262

Answer №1

To retrieve the `result` property from each object, you can use the following code snippet.

var arrCombined = [
        { result: "494,927", risk: "LOW", sector: "Online" },
        { result: "48,883", risk: "MEDIUM-LOW", sector: "Retail Stores" },
        { result: "59,976", risk: "MEDIUM-LOW", sector: "Store Pick up" },
        { result: "1,205,915", risk: "MEDIUM", sector: "Drive in" },
        { result: "1,434,262", risk: "LOW", sector: "In store" }
    ],
    finalResult = arrCombined.map(({ result }) => Number(result.replace(/(,\s*)+/g, '').trim()));

console.log(finalResult);

Answer №2

The reason for the issue you're facing is that you're trying to access the result property from arrCombined, which is undefined, causing your code to not function properly. To fix this, all you need to do is loop through arrCombined using the map method and then access the result property of each object within the array like so:

const arrCombined = [
  { result: "494,927", risk: "LOW", sector: "Online" },
  { result: "48,883", risk: "MEDIUM-LOW", sector: "Retail Stores" },
  { result: "59,976", risk: "MEDIUM-LOW", sector: "Store Pick up" },
  { result: "1,205,915", risk: "MEDIUM", sector: "Drive in" },
  { result: "1,434,262", risk: "LOW", sector: "In store" }
]

let finalResult = arrCombined.map(function (e) {
    return Number(e.result.replace(/(,\s*)+/g, '').trim());
});

console.log(finalResult)

Answer №3

This is the desired outcome.

const finalOutcome = total.finalResult.map(function (element) {
        return Number(element.outcome.replace(/(,\s*)+/g, '').trim());
    });

Answer №4

Here is a solution that may help resolve your problem

We have an array called arrCombined containing data on results, risk level, and sector for different categories. We then use the map function to extract numerical values from the 'result' key in each object by removing commas and whitespace characters. Finally, we output the modified numerical values to the console.

var arrCombined = [
{ result: "494,927", risk: "LOW", sector: "Online" },
{ result: "48,883", risk: "MEDIUM-LOW", sector: "Retail Stores" },
{ result: "59,976", risk: "MEDIUM-LOW", sector: "Store Pick up" },
{ result: "1,205,915", risk: "MEDIUM", sector: "Drive in" },
{ result: "1,434,262", risk: "LOW", sector: "In store" }
]

var finalResult = arrCombined.map(item => {
  return Number(item.result.replace(/(,\s*)+/g, '').trim())
});

console.log(finalResult)

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

Directing a controller assignment in AngularJS 1.2 via a directive

Transitioning from angularJS 1.0 to 1.2 has presented a challenge for me when it comes to assigning a controller to a directive with a distinct scope, without explicitly defining the controller in my HTML using ng-controller. Let's look at this scena ...

Here are some steps for generating a non-integer random number that is not in the format of 1.2321312312

I am looking to create random numbers that are not integers, for example 2.45, 2.69, 4.52, with a maximum of two decimal places. Currently, the generated number includes many decimal places like 2.213123123123 but I would like it to be displayed as 2.21. ...

Struggling to display a chart using angular-chart

I am facing an issue with rendering my chart. I have followed the instructions provided on the GitHub page of angular-chart.js. I have created a plunker to showcase my problem: http://plnkr.co/edit/x7XJhxxvYMzWr3u7lBcJ?p=preview Although I can access and ...

Display or conceal child links using JQuery based on their availability

I have a query regarding JQuery. If I click on Link1, which does not contain any ul.children, the class current_page_item will be added (not shown in this code as it is added automatically by Wordpress). In this scenario, the ul.children in Link2 should be ...

Enzyme locates and chooses the initial occurrence of an element

I am attempting to simulate a click on the initial box out of three. My React script appears as follows: const Boxes = (props) => { return ( <div className="container"> <div onClick={props.showMessage} className="box">One& ...

Use JavaScript to convert only the initial letter to uppercase

Once again, I am in the process of learning! Apologies for the simple questions, but learning is key... Attempting to implement a trick I found online to change all letters to uppercase, I am now trying to adjust it to only capitalize the first letters. T ...

Tips on avoiding asynchronous issues in NodeJS: Ensure task a is finished before initiating task b

I have a situation where I need to ensure that task B code only executes after task A has completed. Task A involves converting an audio file, while Task B relies on the converted audio for further processing. The issue arises because Task A saves the n ...

The function .click does not function properly when used with an anchor element within a figure tag

In my JavaScript-loaded figure, there is an image description and two buttons. Sometimes the description contains a link with a fig attribute, like this: <a fig="allow" href="#tt5">[1]</a> If the anchor is not in a figure and has a fig attrib ...

Replicate the action of clicking on the download button in R

Is there a way to programmatically simulate clicking on the download button on the following website using R and download the TSV table? I have looked into methods such as Rselenium and PhantomJS, but they seem to be outdated now. I came across V8 as a po ...

How to insert a row above the header in an Excel sheet using JavaScript within

i am using excel js to export json data to excel. The json data is successfully exported to the sheet, but now I need to add a row that provides details of the sheet above the header text. for more details please refer image the code is shown below: i ...

What is the reason behind the default disabling of bootstrap multiselect options?

Just diving into the world of bootstrap and I'm puzzled as to why my simple multiselect options aren't responding when clicked. UPDATE The first multiselect option on the test-site linked below is the one giving me trouble. I've tried it o ...

Looking for a way to locate any elements in jQuery that do not contain a certain CSS class?

I am looking to target all form elements that do not contain a specific CSS class. For example: <form> <div> <input type="text" class="good"/> <input type="text" class="good"/> <input type="text" class="bad"/> ...

List application now includes the capability of adding three items in one go, rather than just one

Furthermore, when the script is placed in the same file as the html, it results in the addition of two items simultaneously instead of three. var itemNum = 1; $("document").ready(function() { $("#addCL").click(function() { var itemId ...

Adjust Sidebar Height to Match Document Height (using React Pro Sidebar)

Having an issue with the height of a sidebar component in Next.js using React Pro Sidebar. It seems to be a JavaScript, HTML, and CSS related problem. I've tried several suggested solutions from Stack Overflow, but none of them seem to work. Surprisin ...

Close any open alerts using Protractor

While using protractor and cucumber, I have encountered an issue where some tests may result in displaying an alert box. In order to handle this, I want to check for the presence of an alert box at the start of each test and close/dismiss it if it exists. ...

Executing asynchronous functions synchronously

I am relatively new to JavaScript programming and I am currently trying to grasp the concepts of asynchronous processes. In my project, I am looking to execute the following code synchronously. Despite watching numerous tutorials on the subject, I find mos ...

Clicking on a table will toggle the checkboxes

I am facing an issue with this function that needs to work only after the page has finished loading. The problem arises due to a missing semicolon on the true line. Another requirement is that when the checkbox toggle-all is clicked as "checked", I want ...

How to generate a custom JSON key name in PHP using Laravel

Currently, I am utilizing imagick to extract a number of pages and then store it in JSON format. However, the number is stored as is without any key, for instance - 20. I am seeking a way to store the number with a specific key like below: { "pages": " ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...

Is the array in Java thread-safe when one thread changes the value and another thread reads the value?

I have implemented a simple ringbuffer where one thread is used for the poll() method and another thread is used for the offer() method in the test1() method. I have tested it multiple times and it always returns true. Can someone provide an explanation? ...