0

I have the following array of string that needs to be turn into array of object with the keys value and label

languages: ["Arabic", "Irish"]
           0:"Arabic"
           1:"Irish"
           length: 2

If I wanted to make this array into an array of object like the following:

languages = [
    { value: 'Arabic', label: 'Arabic' }
    { value: 'Irish', label: 'Irish' }
]

How will I do that? Can someone please help?

SamWhite
  • 89
  • 3
  • 11
  • `languages.map(x => ({value:x , label:x}))` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map – ashish singh Aug 15 '18 at 14:08

1 Answers1

2

You can use Array.map():

var languages = ["Arabic", "Irish"];
var res = languages.map(item => ({'value':item, 'label':item}));
console.log(res);

You can also use Array.forEach() as:

var languages = ["Arabic", "Irish"];
var res = [];
languages.forEach(item => res.push({'value':item, 'label':item}));
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62