Exploring the contents of the response object

I'm facing what seems to be a minor issue that I can't seem to resolve. The response body I have looks like this:

{
    "sizes": [
        {
            "43": 35
        },
        {
            "42": 20
        },
        {
            "38": 10
        }
    ]
}

with the keys representing shoe sizes and the values indicating the quantity for each size. How can I access these sizes effectively? Currently, my approach is as follows:

const sizesArray = response.data.sizes

const arr = Object.values(msizes);
    console.log('arr', arr);
    arr.map((i,a) => {
        console.log('i',i);
        console.log('a',a);
    })

However, 'i' turns out to be another object {43: 35} and 'a' is simply the index. I want to somehow assign the key to a parameter called 'sizes' and the value to a parameter called 'quantity'.

https://codesandbox.io/s/confident-ishizaka-rqjvbv?fontsize=14&hidenavigation=1&theme=dark

Answer №1

To simplify retrieving keys from an object in JavaScript, consider using Object.keys instead of Object.entries

For example:

const data = { sizes: [{ "43": 35 }, { "42": 20 }, { "38": 10 }] };

const result = data.sizes.map((element, index) => {
  let obj = Object.keys(element); // retrieve keys as an array
  let key = obj[0]; // get the first key
  let quantity = element[key]; // access value using the retrieved key
  console.log("size", key);
  console.log("quantity", quantity);
});

Answer №2

To extract the keys from objects in the sizes array, you can use the reduce method and store them in an output array:

const data = { sizes: [{ "43": 35 }, { "42": 20 }, { "38": 10 }] }

const sizes = data.sizes.reduce((acc, s) => acc.concat(Object.keys(s)), [])

console.log(sizes)

If you need both sizes and quantities, a similar approach can be taken. Create an object that accumulates both sets of values:

const data = { sizes: [{ "43": 35 }, { "42": 20 }, { "38": 10 }] }

const { sizes, quantities } = data.sizes
  .reduce((acc, s) => {
     acc.sizes = acc.sizes.concat(Object.keys(s))
     acc.quantities = acc.quantities.concat(Object.values(s))
     return acc
   },
   { sizes : [], quantities : [] })

console.log(sizes)
console.log(quantities)

Answer №3

You're definitely on the right path :)

Try using Object.keys() to extract an array which contains all your keys (shoe sizes). After that, utilize the map() function to generate a new array. Use the index within the map() method to retrieve the quantity from your response.

const sizesArray = response.data.sizes

const sizes = Object.keys(sizesArray);
const result = sizes.map((element, index) => ({
  size: element, 
  quantity: sizesArray[index]
}));

console.log(result);

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

Parsing and encoding JSON data involves traversing a multi-dimensional array and eliminating key-value pairs that match a specific value

Essentially, the PHP-generated JSON output looks like this. [{"attr":{"id":"node_2","rel":"default"},"data":"C:","state":"closed"},{"attr":{"id":"node_3","rel":"drive"},"data":"D:","state":"closed"}] Since the 'rel' attribute is set to 'de ...

What is the best method for providing an argument to JavaScriptCore/Console through the terminal or another method?

JSC appears to be a straightforward and convenient option‒more portable, quasi-universally-installed alternative to node.js... I have managed to grasp the basics but there seems to be very minimal information available (why?), so here's an issue tha ...

How can I display Google Maps markers on my map?

I have successfully created my map, but I am facing an issue with getting markers or clusters to appear on it. Below is the JavaScript code I am using: function initMap() { var map = new google.maps.Map(document.getElementById("map"), { z ...

What is the best way to handle JSON with unconventional syntax in an Android application?

When attempting to handle the JSON string on an Android device, I encountered an org.json.JSONException error. org.json.JSONException: Value {"alias":"\ud56b\u at org.json.JSON.typeMismatch(JSON.java:100) at org.json.JSONArray.getJSONObject(JSON ...

Troubleshooting problem with Bootstrap tabs and jQuery event triggering

Being new to JavaScript and jQuery, I am encountering issues with some basic things. I have set up 3 bootstrap tabs: (mainstream, substream, delayedstream). Within each tab, I have included a VLC player using jQuery, and the players are functioning perfec ...

Tactile interactions on iPhone

My goal is to create an off-canvas menu that can be opened with touch events in a systematic way. It functions perfectly in my browser when I click and drag on the body to reveal the menu. However, it encounters a problem on the iPhone. The error message ...

Tips for incorporating a PDF file into a website when the Adobe Reader add-on is disabled in Internet Explorer

I attempted to insert a PDF into my website using the <embed> tag. Unfortunately, it doesn't seem to be functioning properly in Internet Explorer when the Adobe Reader add-on is disabled. Is there a solution that will allow it to work even if th ...

Why is the useHistory hook in React failing to function properly?

When I try to launch my web application using npm start, an error occurs stating that the useHistory hook has not been downloaded, despite having installed the latest version of react-router-dom. Can someone explain why this is happening? Here is a screens ...

How can I force an element to overflow without being affected by its parent's overflow style in CSS/HTML/JS, even if the parent is

I've come across many inquiries on this subject, but the proposed solutions never seem to work when dealing with ancestors that have absolute positioning. Take this example: <div id='page'> <div id='container' style= ...

Internet Explorer does not support the shorthand for defining associative arrays in Javascript

I've implemented an ajax post to the server using the code below: $.post( "/api/server_login.php", { variable_1, variable_2 }, function( json ) {... The array in the middle is a shorthand representation of: $.post( "/api/server_login.php", { vari ...

Encountered an error while trying to create a new NestJS project using yarn: Command execution failure - yarn install --

Having trouble installing a new NestJs project using yarn. Operating system : Microsoft Windows [version 10.0.19044.3086] Node version : 18.17.1 npm version : 9.6.7 yarn version : 1.22.19 Nest cli version : 10.1.16 I attempted to install by running : npm ...

CORS request results in unsuccessful cookie setting in browsers except for Firefox where Set-Cookie header is detected; notably, Chrome does not show the header

I'm experiencing an issue with setting cookies from a NodeJS server to the client using JQuery and AJAX. Despite seeing the Set-Cookie headers in the response, the cookies are not showing up in the document.cookie string. I would greatly appreciate it ...

JavaScript transforming an array into a counter

I am seeking a way to transform a one-dimensional array into a frequency dictionary in JavaScript. The array elements should serve as keys, while their frequencies act as values. Take, for example, the Python script below, which generate a list of 1024 ra ...

Interacting with directive scope beyond controller boundaries

Developing a custom directive within a controller and implementing it in an ng-repeat loop: HTML: <div ng-controller="TestCtrl"> <div ng-repeat="page in pages"> <custom load-data="loadData = fn"></custom> </div> ...

Tips for illustrating the connection between two distinct schemas during a discussion

I am facing an issue where I need to consider two different Schemas that can be used in place of the user property within the Conversation model. How should I approach representing this? It could either be a Student who has messaged or a User who sends a m ...

Error message "mapStateToProps() in Connect(ModalRoot) must return an object literal. Received undefined." was thrown by the React-Redux container

I have been working on creating a Redux based Model/Dialog trigger inspired by Dan Abramov's solution to a similar problem on Stack Overflow. However, I encountered an error message saying "mapStateToProps() in Connect(ModalRoot) must return a plain ...

What steps should I take to resolve the "undefined property match cannot be read" error that's showing up in this code?

Currently, I am facing an issue while attempting to integrate the nativescript-imagepicker plugin into my Nativescript App. I keep receiving an error message stating **cannot read **property match of undefined**. Below is a summary of the steps I have take ...

Serializing dates in JSON format in ASP.NET RESTful services

Currently, I am working on developing REST API's that return data in JSON format. ASP.net is responsible for serializing the data, resulting in an output like below: [ { "DueDate": "/Date(1338316200000+0530)/", "User": "XYZ" } ] My goal ...

Convert form data into a JSON object utilizing JQuery and taking into account nested JSON objects

Currently, I am facing an issue while extracting data for submission using the jQuery `serializeArray()` function. This function works efficiently by providing an array of { name: value } objects, where the name corresponds to the elements in the form. How ...

Directive @input: Hold until the user completes their query

As I navigate through my Vue learning curve, I've observed that the input field triggers an AJAX call (using axios) to YouTube with every keystroke entered. This means that even a single letter prompts a search query to be executed on the YouTube sear ...