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,7667 gold badges26 silver badges52 bronze badges
asked Nov 1, 2020 at 17:36
3
  • 3
    Where's that "place" stuff coming from? And you result looks like a Javascript object, no JSON text involved. Commented Nov 1, 2020 at 17:38
  • 1
    Maybe here you can find the answer stackoverflow.com/questions/2295496/convert-array-to-json Commented Nov 1, 2020 at 17:40
  • ''place" can obviously be treated as a constant keyword Commented Nov 1, 2020 at 17:41

4 Answers 4

13

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);

answered Nov 1, 2020 at 17:40
Sign up to request clarification or add additional context in comments.

Comments

4

var array = [1, 2, 3, 4];
const jsonObj = {}
array.forEach((v,i) => jsonObj['place'+i] = v);
console.log(jsonObj)

answered Nov 1, 2020 at 17:41

Comments

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);

answered Nov 1, 2020 at 17:43

1 Comment

Just another way to do it.
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)

answered Nov 1, 2020 at 17:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.