Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!