简体   繁体   中英

Convert array to JSON object using JS

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}

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

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

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

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)

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