Function for mapping: Array with nested objects will not be printed one after the other

Looking at the function below, I aim to map _s from res to another function using the return value from the manipulateValidateReqRes function

CODE WAS UPDATED BELOW

Why am I unable to return _s from the map function on res? It displays an error: TypeError: Object has no member 'map'

UPDATE

To provide a clear explanation and update the debugging process, here is my latest code snippet

const res = {
            "valid_data": [
                {
                    "shipper_name": "automate sender1",
                    "rts_reasons": [
                        "a reason"
                    ],
                    "rts_score": 0
                },
                {
                    "shipper_name": "automate sender2",
                    "rts_reasons": [
                        "a reason"
                    ],
                    "rts_score": 0
                }
            ],
            "shipping_rates": [
                {
                    "reguler": {
                        "summary_price": "7.000",
                        "data": [
                            {
                                "_s": "9917xxx",
                            }
                        ]
                    },
                    "express": {
                        "summary_price": "15.000",
                        "data": [
                            {
                                "_s": "9918xxx"
                            }
                        ]
                    }
                }
            ],
            "errors": [
                [],
                []
            ]
        }

      const manipulateRequest = Object.values(res).map((obj) => {
  return {
                shipper_name: res.valid_data[0].shipper_name
  }
  })
  
  const postBulkPayload = {
    "filename": "filename1.xlsx",
    "total_order": manipulateRequest.length,
    "is_use_new_payment": true,
    "template_name": "bulk-order-with-postal_code-and-sub_district_name",
    "details": manipulateRequest,
    "cancelToken": {
        "promise": {}
    }
}
  console.log(postBulkPayload)

The result shows:

{
  filename: 'filename1.xlsx',
  total_order: 3,
  is_use_new_payment: true,
  template_name: 'bulk-order-with-postal_code-and-sub_district_name',
  details: [
    { shipper_name: 'automate sender1' },
    { shipper_name: 'automate sender2' },
    { shipper_name: 'automate sender1' }
  ],
  cancelToken: { promise: {} }
}

Why isn't 'automate sender2' being printed?

Answer №1

The reason behind the specific error you're encountering is due to the JSON being returned as an object, which does not support a .map method. One solution is to utilize the Object.values method in this manner:

const manipulateRequest = Object.values(res).map((obj, index) => {
     return {
                    _s: res.data.shipping_rates[index].regular.data[index]._s
    }
}

However, it's unclear what your intention is with this code that returns an object containing the _s property. Presumably, you aim to extract the value of the _s property and save it in the manipulateRequest array like so:

const manipulateRequest = Object.values(res).map((obj, index) => {
     return obj.shipping_rates[index].regular.data[index]._s;
}

It might be beneficial to implement some validation to verify the existence of properties and correctness of data types.

Furthermore, utilizing the index for the res object to access the shipping_rates array and the data array won't yield the desired outcome.

To simplify testing, you could just retrieve the first element from the shipping_rates array:

const manipulateRequest = Object.values(res).map((obj, index) => {
     return {
                    _s: res.data.shipping_rates[0].regular.data[0]._s
    }
}

Note that I substituted the index variable with a static 0 index. While this approach will function, it may not accommodate any future changes in the data structure.

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 "smiley" character added to the information during an Ajax call

Encountering an unusual issue. A colon (:) character is being appended to the JSON data sent to the server via AJAX request. https://example.com/image1.png The colon character seems to appear after sending the JSON, but it does not show up when inspectin ...

Jackson ObjectMapper configured to represent JSON data in array format without using annotations

Is there a way to use two Jackson 2 object mappers for the same set of classes? The first mapper needs standard serialization, while the second should use the ARRAY shape type for all classes. I want to globally set this feature for my second ObjectMapper, ...

Integrating a secondary array within the foreach loop

I have a situation where I have two dynamic input fields, and the number of subsequent fields can vary from form to form. To capture the field inputs, I am using an array. Currently, the script inserts an autoincremented ID from a previous query and also ...

How to efficiently deserialize JSON into a List of objects using Kotlin and Jackson without encountering a Deserialization Exception

I have been using the following link to learn how to read values using a mapper from a JSON string, but I encountered a deserialization exception while executing my code. How to use jackson to deserialize to Kotlin collections Code: private fun parseCou ...

Getting the environment variable from Rails in your JavaScript: A guide

I am currently working on implementing a key system within my application. In the code I am using, there is logic that looks like this: $('.key-test-button').on('click', function(){ if ($('.key-test-input').val() === "MYK ...

In order to prevent redundancy in your Angular 2+ project, make sure to set

I recently organized my app by creating different modules such as auth, admin, and main. However, I noticed that I have the same imports in each module: import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angul ...

Is it possible to change the tab to "home-tab" by clicking on navbar-brand in Bootstrap 5 using JavaScript?

This is my first venture into web development, so please bear with me as I navigate through this unfamiliar territory. In my project, I have a function called Navbar() that generates a navigation bar on the webpage by wrapping all elements with the navbar ...

Concealing and revealing information with jQuery and AJAX

Need help hiding a Message and displaying an alert message after 5 seconds, but it's not working. What I want is for the Message to be hidden and show an alert message 5 seconds after clicking submit. <script> $(document).ready(function () { ...

Encountered a type mismatch in Flutter where an 'int' was expected but a 'String' was provided instead

Recently, I've been diving into creating a quotes app that utilizes a rest API to fetch data and display random quotes at the center of the screen with just a tap. However, I seem to be encountering some hurdles in getting everything to function as in ...

Web application experiencing issues with electron loading and functioning properly

I attempted to load a web application in electron using window.loadurl and as a webview in html. The application is displaying, but encountering various errors such as: $ jquery not defined Uncaught TypeError: $(...).daterangepicker is not a function Unca ...

preventing firefox from highlighting text on a webpage

Similar Question: What's the most effective method to prevent text highlighting when clicking inside a div using JavaScript? Is there a way to prevent Firefox from highlighting content when a user clicks and drags? ...

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...

Having trouble displaying dynamically generated texture from a fragment shader in ThreeJS

I've been working on creating a texture using a Three.WebGLRenderTarget and then trying to access it in a fragment shader in the following stage. The concept is to execute the first stage once to generate a complex and costly SDF map, and then access ...

Start up a server using Angular along with Node.js and Express framework

I am encountering an issue with configuring Express as a server in my Angular application. The app loads without any issues when accessing the HOME route, but when trying to access another route, I receive an error message: Cannot GET / This is how I hav ...

Prevent the function from being triggered repeatedly while scrolling

When a user scrolls to the bottom of the page, the following code is meant to load the next page. However, there are instances where it repeats itself due to rapid scrolling or while the AJAX content is still loading. Is there a way to prevent this code f ...

Master the ins and outs of working with Angular and Webpack on

Encountering issues with the webpack-angular tutorial from egghead.io during the "ES6 with Babel" step. Requesting assistance in resolving the problem. Stuck at this specific step while following the tutorial: Error message in Chrome devTools: ........ ...

Display a container upon clicking a button if the field is valid

Having recently delved into the world of jQuery, I encountered a challenge with a plugin called jQuery Validate. Despite searching for examples on their website, none seemed to match my unique situation. After experimenting with different approaches, I st ...

Unlocking the power of conditional array data retrieval in PHP

In my temp.txt file, I have the following data: -------------------| -------------------V 2016/11/2 23:49:34,1,2,3,5 <---Array 0 2016/11/2 23:49:35,2,2,3,9 <---Array 1 2016/11/2 23:49:36,0,2,3,5 <---Array 2 2016/11/2 23:49:37,0,5,3,5 <---Array ...

Is it advantageous to combine socket.io with express for seamless communication in web applications? If the answer is yes, what is the best approach to integrating

Embarking on my journey into back-end development, I am currently delving into the task of creating a simulated money poker website. Leveraging Node.js along with socket.io, express-session, and passport, I initially relied heavily on express with an HTTP ...

What is the best way to assign the innerText/innerContent of a list with the values from a multidimensional array?

As a newcomer to JavaScript, I apologize if the code is not up to par. My goal is to allow users to select a state from a form and display 5 cities. This is the current code snippet: HTML with Bootstrap classes <div class="row row1"> <div class= ...