最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert array to JSON object using JS - Stack Overflow

programmeradmin6浏览0评论

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}

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}
Share Improve this question edited Nov 1, 2020 at 23:21 Sarun UK 6,7467 gold badges24 silver badges49 bronze badges asked Nov 1, 2020 at 17:36 Oleg OmOleg Om 4396 silver badges16 bronze badges 3
  • 3 Where's that "place" stuff coming from? And you result looks like a Javascript object, no JSON text involved. – Bergi Commented Nov 1, 2020 at 17:38
  • 1 Maybe here you can find the answer stackoverflow.com/questions/2295496/convert-array-to-json – lissettdm Commented Nov 1, 2020 at 17:40
  • ''place" can obviously be treated as a constant keyword – EugenSunic Commented Nov 1, 2020 at 17:41
Add a comment  | 

4 Answers 4

Reset to default 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);

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)

发布评论

评论列表(0)

  1. 暂无评论