-1

My initial object is:

const initObject = {"ITEM1": "Item 1", "ITEM2: "Item 2"}

How to convert it to:

​const convertedArray = [{value: "ITEM1", label: "Item 1"}, {value: "ITEM2", label="Item 2"}]

Italik
  • 696
  • 2
  • 18
  • 35
  • Does this answer your question? [How to transpose a javascript object into a key/value array](https://stackoverflow.com/questions/36411566/how-to-transpose-a-javascript-object-into-a-key-value-array) – User863 May 20 '21 at 13:56

3 Answers3

2

You can try map through the object keys to create the array using Object.keys() and Array.prototype.map() like the following way:

const initObject = {"ITEM1": "Item 1", "ITEM2": "Item 2"};
const convertedArray = Object.keys(initObject).map(k => ({value: k, label: initObject[k]}));
console.log(convertedArray);

Note: You have missed closing" in key in "ITEM2: "Item 2"

Mamun
  • 66,969
  • 9
  • 47
  • 59
0

You can use Object.entries to get a list of key value pairs on which you can loop on and create your array.

const initObject = {"ITEM1": "Item 1", "ITEM2": "Item 2"};
const convertedArray = Object.entries(initObject).map(([key, value]) => ({value: key, label: value}));
console.log(convertedArray);
litelite
  • 2,857
  • 4
  • 23
  • 33
0
const convertedArray = Object.keys(initObject).map((x)=> { return {
   value : x,
 label: initObject[x]
}});
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39