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

79
Views
Convert Array to Object for table Schema

What is the best way to convert:

["Foo", "Bar", "John"]

To:

{
Foo: { name: 'Foo', index: 0, type: 'String' },
Bar: { name: 'Bar', index: 1, type: 'String' },
John: { name: 'John', index: 2, type: 'String' },
}

I believe I need to utilize

array.map()

but am not sure how to structure my mapping function. Any insight would be helpful.

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

0

You can the function Array.prototype.reduce as follow.

const source = ["Foo", "Bar", "John"],
  capitalize = string => string.charAt(0).toUpperCase() + string.slice(1),
  result = source.reduce((a, name, index) => ({...a, [name]: {name, index, type: capitalize(typeof name)}}), {});
  
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

your json is not valid , so if you need the valid json like this

[{"name":"Foo","index":0,"type":"string"},{"name":"Foo","index":1,"type":"string"},{"name":"Foo","index":2,"type":"string"}]

you can use this code

var result=[];
arr.forEach( (element,i )=> {
  result.push( {name:element, index:i, type: typeof element});
 });

UPDATE

for your another json

var jarr=["Foo", "Bar", "John"]

you can use this code

var result = {};
jarr.forEach((element, i) => {
  result[element] = { name: element, index: i, type: typeof element };
});

result

{
  "Foo": {
    "name": "Foo",
    "index": 0,
    "type": "string"
  },
  "Bar": {
    "name": "Bar",
    "index": 1,
    "type": "string"
  },
  "John": {
    "name": "John",
    "index": 2,
    "type": "string"
  }
}
about 4 years ago · Juan Pablo Isaza Report

0

I think you could do as follows

const array = ["Foo", "Bar", "John"];
Object.fromEntries(
   array
   .map((el, index) => {
     return [el, {name: el, index, type: el.constructor.name}]
   })
)

Here you can find an example snippet:

const array = ["Foo", "Bar", "John"];
const result = Object.fromEntries(
   array
   .map((el, index) => {
     return [el, {name: el, index, type: el.constructor.name}]
   })
);
console.log(result);

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!