Reputation: 1031
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
Reputation: 54016
use Object.assign
const a = ['a', 'b', 'c'];
const newObject = Object.assign({}, a);
console.log(newObject);
Upvotes: 0
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
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