hanku8
hanku8

Reputation: 77

Accessing the body of the response object

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

Upvotes: 1

Views: 2858

Answers (3)

chrisjung
chrisjung

Reputation: 19

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(sizesArray);
const result = sizes.map((element, index) => ({
  size: element, 
  quantity: sizesArray[index]
}));

console.log(result);

Upvotes: -1

Nick
Nick

Reputation: 147216

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)

If you want sizes and quantities, you can take a similar approach, just generate an object which 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)

Upvotes: 1

rodrigo cordova
rodrigo cordova

Reputation: 71

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

Upvotes: 2

Related Questions