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.
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);
function mapper(key){ return JSON.stringify(arrayEx.map(a => ({[key]: a}));}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With