Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda