简体   繁体   中英

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?

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']}]

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.

use Object.assign

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM