-6
const myArray =  ['position zero', 'position one', 'position three', 'position four'];

// i neeed to convert it to

const objectArray = [
    {
        position: 'position zero'
    },
    {
        position: 'position one'
    },
    {
        position: 'position three'
    },
    {
        position: 'position four'
    },
];

// must the same key which i will be refer to all

laruiss
  • 3,780
  • 1
  • 18
  • 29

4 Answers4

3

map over your current array and return the object from map function

const myArray =  ['position zero', 'position one', 'position three', 'position four'];

const res = myArray.map(data => {
    return {position: data}
})

console.log(res)
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

You can use array#map with Shorthand property names.

const myArray =  ['position zero', 'position one', 'position three', 'position four'],
      result = myArray.map(position => ({position}));
console.log(result);
.as-console-wrapper { max-height:100% !important; top:0;}
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

You can use .map() here:

const result = myArray.map(s => ({position: s}));

Demo:

const myArray =  ['position zero', 'position one', 'position three', 'position four'];

const result = myArray.map(s => ({position: s}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Docs:

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0

User array.map with ES6's shorthand object litteral:

const myArray =  ['position zero', 'position one', 'position three', 'position four'];

const res = myArray.map(position => ({position}));
console.log(res);
Faly
  • 13,291
  • 2
  • 19
  • 37