skip to Main Content

What is the fastest algorithm for getting from something like this:

var array = [ 'a','b','c','d','e' ];

to something like this:

[{label:'a',value:'a'},{label:'b',value:'b'},{label:'c',value:'c'},{label:'d',value:'d'},{label:'e',value:'e'}]

2

Answers


  1. var array = [ 'a','b','c','d','e' ];
    const result = array.map(l => ({label: l, value: l}))
    
    Login or Signup to reply.
  2. You can use array.map function to covert the array into required object. In your case something like this would generate the required result

    var array = [ 'a','b','c','d','e' ];
    var result = array.map(function (element) {
        return {
            'label': element,
            'value': element
        };
    });
    

    you can refer to the full documentation for map here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search