4

help please with converting array to JSON object

var array = [1, 2, 3, 4]; 
var arrayToString = JSON.stringify(Object.assign({}, array));
var stringToJsonObject = JSON.parse(arrayToString);
 
console.log(stringToJsonObject);

I try this and get:

{0: 1, 1: 2, 2: 3, 3: 4}

Expected result

{place0: 1, place1: 2, place2: 3, place3: 4}
Sarun UK
  • 6,210
  • 7
  • 23
  • 48
Oleg Om
  • 429
  • 5
  • 15

4 Answers4

12

You can do this with .reduce:

var array = [1, 2, 3, 4]; 

var res = array.reduce((acc,item,index) => {
  acc[`place${index}`] = item;
  return acc;
}, {});
 
console.log(res);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
4

var array = [1, 2, 3, 4];
const jsonObj = {}
array.forEach((v,i) => jsonObj['place'+i] = v);
console.log(jsonObj)
Sarun UK
  • 6,210
  • 7
  • 23
  • 48
0

You can use Object.entries() to get all the array elements as a sequence of keys and values, then use map() to concatenate the keys with place, then finally use Object.fromEntries() to turn that array back into an object.

There's no need to use JSON in the middle.

var array = [1, 2, 3, 4]; 
var object = Object.fromEntries(Object.entries(array).map(([key, value]) => ['place' + key, value]));
console.log(object);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Using for of loop and accumulating into the object

var array = [1, 2, 3, 4];
const result = {}
for (let item of array) {
  result['place' + item] = item;
}
console.log(result)
EugenSunic
  • 13,162
  • 13
  • 64
  • 86