Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript array to JSON with user defined key

Is there a clean efficient method of converting a basic 1 dimensional array such as:

arrayEx = [1,2,3,4]

into a user defined JSON array such as:

jsonArrayEx = [{"exampleKey": 1}, {"exampleKey": 2}, {"exampleKey": 3}, {"exampleKey": 4}]

I have seen examples on using JSON.Stringify where the key is based on the index of the array but nothing with the key defined by the user as shown in my example.

like image 529
Qiuzman Avatar asked Apr 12 '26 21:04

Qiuzman


2 Answers

You can use Array#map with a computed property name when creating a new object.

const arr = [1,2,3,4];
let key = "exampleKey";
const res = arr.map(x => ({[key]: x}));
console.log(res);
like image 151
Unmitigated Avatar answered Apr 15 '26 14:04

Unmitigated


function mapper(key){ return JSON.stringify(arrayEx.map(a => ({[key]: a}));}

like image 22
Totati Avatar answered Apr 15 '26 14:04

Totati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!