Ras
Ras

Reputation: 1031

Convert array to object wrapped with square brackets [ ]

I'm already looking in Convert Array to Object but it looks different. I mean, how i can convert array to object with the square brackets format at the start and end of the object?

Array :

['a','b','c']

to :

[
  {
    0: 'a',
    1: 'b',
    2: 'c'
  }
]

Anyone can help?

Upvotes: 0

Views: 1064

Answers (3)

xkeshav
xkeshav

Reputation: 54016

use Object.assign

  const a = ['a', 'b', 'c'];
  const newObject = Object.assign({}, a);
  console.log(newObject);

Upvotes: 0

Omprakash Sharma
Omprakash Sharma

Reputation: 429

There is various way to achieve this, try with Array.forEach method ,

var orgArrayData = ['a','b','c','d'];
var convertedFormatData = [];
var tempObj = {};
convertArrayElemToObject(orgArrayData);
function convertArrayElemToObject(orgArrayData){
    orgArrayData.forEach((element,index)=>{
        tempObj[index] = element;
    });
};
convertedFormatData.push(tempObj);
console.log(convertedFormatData);

o/p -

[
  0: {0: "a", 1: "b", 2: "c", 3: "d"}
]

i hope, it will help to you.

Upvotes: 1

Andrew Hare
Andrew Hare

Reputation: 351516

Use the toObject function from the answer you mentioned and wrap the result in an array:

[toObject(['a', 'b', 'c'])]

Or if you are using ES6+, you can do:

[{...['a', 'b', 'c']}]

Upvotes: 3

Related Questions