-1

I have the following object:

{
    "thumbnail": {
        "height": 150,
        "width": 150,
    },
    "medium": {
        "height": 165,
        "width": 300,
    },
    "large": {
        "height": 352,
        "width": 640,
    }       
}

I want to create the following array from the object.

[
    {
        "slug": "thumbnail",
        "name": "Thumbnail"
    },
    {
        "slug": "medium",
        "name": "Medium"
    },
    {
        "slug": "large",
        "name": "Large"
    },
    {
        "slug": "full",
        "name": "Full"
    }
]

How can I get the object key name to add to the array? I tried the following:

map( imageSizesArray,
   ( { key } ) => ( { value: key, label: key.toUpperCase() } )
);

but it does not work

CyberJ
  • 1,018
  • 1
  • 11
  • 24
  • Just use `Object.keys(obj)[0]` to get the key in the callback. – VLAZ Nov 11 '21 at 07:03
  • where did `value` came from. Shouldn't it be `slug`? – h-sifat Nov 11 '21 at 07:09
  • @VLAZ in your closed link the OP start with an array, here the OP start with an object, CyberJ use directly `Object.keys` [reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys?retiredLocale=en) – Simone Rossaini Nov 11 '21 at 07:09
  • @SimoneRossaini there is three links. And each has at least one answer for how to get the keys of an object. – VLAZ Nov 11 '21 at 07:13
  • @SimoneRossaini removed the first link which was for arrays and added two more that are for extracting keys. Overall, I feel like the subject has been sufficiently covered but feel free to suggest more duplicates. There are five slots in total. – VLAZ Nov 11 '21 at 07:16
  • @VLAZ I think the work you have done is enough :) – Simone Rossaini Nov 11 '21 at 07:27

1 Answers1

2

const obj = {
    "thumbnail": {
        "height": 150,
        "width": 150,
    },
    "medium": {
        "height": 165,
        "width": 300,
    },
    "large": {
        "height": 352,
        "width": 640,
    }       
}

const retrnArr = Object.keys(obj).map(e =>{
return  { 'value': e , 'label' : e.toUpperCase()}
});
console.log(retrnArr)
Toxy
  • 696
  • 5
  • 9