Qiuzman
Qiuzman

Reputation: 1739

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.

Upvotes: 3

Views: 1906

Answers (3)

Salomi Edward
Salomi Edward

Reputation: 543

let arr= [1,2,3,4];
let newArr = [];
for(let i of arr){
  newArr.push({"exampleKey" : i});
}
 
  console.log(newArr);

Upvotes: 1

Totati
Totati

Reputation: 1582

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

Upvotes: 2

Unmitigated
Unmitigated

Reputation: 89294

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

Upvotes: 4

Related Questions