-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

6
  • Just use Object.keys(obj)[0] to get the key in the callback. Commented Nov 11, 2021 at 7:03
  • where did value came from. Shouldn't it be slug? Commented Nov 11, 2021 at 7: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 Commented Nov 11, 2021 at 7:09
  • @SimoneRossaini there is three links. And each has at least one answer for how to get the keys of an object. Commented Nov 11, 2021 at 7: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. Commented Nov 11, 2021 at 7:16

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.