Home > database >  Accessing the body of the response object
Accessing the body of the response object

Time:09-13

I am having what I think is a pretty trivial problem but somehow I can't find a solution to. I have a response body that looks like this:

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

where the keys are shoe sizes and the value is quantity of each size. How do I access the sizes? What I currently have is this:

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);
    })

but i is then again a object {43: 35} and a is just the index. I want somehow to assign the key to parameter called 'sizes' and the key to a parameter called quantity.

Edit confident-ishizaka-rqjvbv

CodePudding user response:

You can use Object.keys, a bit simpler than Object.entries

Example:

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

const result = data.sizes.map((element, index) => {
  let obj = Object.keys(element); // returns an array of keys
  let key = obj[0]; // first element is the only key
  let quantity = element[key]; // bracket notation, key is an string, not number
  console.log("size", key);
  console.log("quantity", quantity);
});

CodePudding user response:

You can just iterate the sizes array, using reduce to append the keys of each object to an output array of sizes:

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

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

console.log(sizes)

CodePudding user response:

You were on the right track :)

Use Object.keys() to get an array of your keys (shoe-sizes). Then use the map()-function to create a new array. Use the index of map() to access the quantity in your response.

const sizesArray = response.data.sizes

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

console.log(result);
  • Related