0

I want to convert an Array like:

[ 'John', 'Jane' ]

into an array of object pairs like this:

 [{'name': 'John'}, {'name':'Jane'}]

Please help me to do so..

  • You want [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). – Alexander Nied Oct 11 '19 at 03:59
  • `var arr = ['John', 'Jane']; var mapped = arr.map(name => ({name}));` – joyBlanks Oct 11 '19 at 04:01
  • Familiarize yourself on [how to access and process nested objects, arrays or JSON](https://stackoverflow.com/q/11922383/4642212) and use the available [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods_of_the_Object_constructor) and [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods) methods. – Sebastian Simon Oct 11 '19 at 04:16

2 Answers2

10

Try the "map" function from the array:

const output = [ 'John', 'Jane' ].map(name => ({name}));
console.log(output);
Pak Wah Wong
  • 506
  • 3
  • 8
0

You can use the instance method .map() on a JS list Object as follows :

 let list = ['John', 'Jane']
 list = list.map(x => {
    return({name: x});
                      });
 console.log(list);