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
-
3Where's that "place" stuff coming from? And you result looks like a Javascript object, no JSON text involved.Bergi– Bergi2020年11月01日 17:38:24 +00:00Commented Nov 1, 2020 at 17:38
-
1Maybe here you can find the answer stackoverflow.com/questions/2295496/convert-array-to-jsonlissettdm– lissettdm2020年11月01日 17:40:21 +00:00Commented Nov 1, 2020 at 17:40
-
''place" can obviously be treated as a constant keywordEugenSunic– EugenSunic2020年11月01日 17:41:40 +00:00Commented Nov 1, 2020 at 17:41
4 Answers 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);
answered Nov 1, 2020 at 17:40
Majed Badawi
28.6k4 gold badges30 silver badges56 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Sarun UK
6,7667 gold badges26 silver badges52 bronze badges
Comments
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
Barmar
789k57 gold badges555 silver badges669 bronze badges
1 Comment
Barmar
Just another way to do it.
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
EugenSunic
13.8k15 gold badges68 silver badges97 bronze badges
Comments
lang-js