-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,652
  • 1
  • 16
  • 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
  • 246,420
  • 52
  • 367
  • 373
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
  • 20,493
  • 5
  • 36
  • 47
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
  • 34,173
  • 19
  • 88
  • 85
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
  • 12,802
  • 1
  • 18
  • 35