0

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?

Ras
  • 991
  • 3
  • 13
  • 24
  • I'm very confused as to what you are asking for.... please read [how to ask](https://stackoverflow.com/help/mcve) – Mike Tung Feb 20 '18 at 03:27
  • 2
    Wouldn't this `res = [{...arr}]` solve the issue you're having? Where `arr=['a','b','c']` – Sudheesh Singanamalla Feb 20 '18 at 03:30
  • @MikeTung. I'm sorry for make you confused, i mean convert array to object with the square brackets format at the start and end object like my second example code above. – Ras Feb 20 '18 at 03:33
  • just wrap the result of the answers in the almost identical question in `[]` - the question you linked to has answers that result in `{0: 'a' ... etc}` ... wrap that in `[]` and you get `[{0: 'a' ... etc}]` – Jaromanda X Feb 20 '18 at 03:38
  • @JaromandaX, can you show me how to do that? I have tried `var obj = arr.reduce(function(acc, cur, i) { acc[i] = cur; return acc; }, []);` i change the {} to [] and the result just `[0: 'a', 1: 'b', 2: 'c']`. how can i get `[{0: 'a', 1: 'b', 2: 'c'}]`. Sorry i'm newbie. – Ras Feb 20 '18 at 04:00
  • see answer below ... or `var obj = [{...array}]` – Jaromanda X Feb 20 '18 at 04:01
  • by the way, you won't actually get what you "want" ... because object keys are always strings – Jaromanda X Feb 20 '18 at 04:03

3 Answers3

3

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']}]
Sampson Crowley
  • 1,244
  • 1
  • 9
  • 22
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • Thank you for you respond, but can you please show how to do that? i don't understand because i'm newbie. – Ras Feb 20 '18 at 04:03
1

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.

Omprakash Sharma
  • 409
  • 5
  • 11
0

use Object.assign

  const a = ['a', 'b', 'c'];
  const newObject = Object.assign({}, a);
  console.log(newObject);
xkeshav
  • 53,360
  • 44
  • 177
  • 245