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

139
Visualizações
How do I populate an array of objects where every object has an array inside of it using response from rest API?

I can't google the right solution for this for about an hour straight, So I'm getting a response from the API that looks like this:

[
  {
    "Name": "name1",
    "Title": "Name One",
    "Children": [
      {
        "Name": "Name 1.1",
        "Title": "Name one point one"
      },
     ]

And I need it to fit this kind of "mold" for the data to fit in:

{
title: 'Name One',
value: 'name1',
key: '1',
children: [
  {
    title: 'Name one point one',
    value: 'Name 1.1',
    key: 'key1',
  },

I am trying to achieve this using a foreach but It's not working as intended because I need to do this all in one instance of a foreach. Here's what I gave a go to(vue2):

   created() {
    getData().then(response => {
      const formattedResponse = []
      response.forEach((el, key) => {
        formattedResponse.title = response.Title
        formattedResponse.name = response.Name
        formattedResponse.children = response.Children
      })
    })
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use map over the main array and use destructuring assignment to extract the properties by key, and relabel them, and then do exactly the same with the children array. Then return the updated array of objects.

const data=[{Name:"name1",Title:"Name One",Children:[{Name:"Name 1.1",Title:"Name one point one"}]},{Name:"name2",Title:"Name Two",Children:[{Name:"Name 1.2",Title:"Name one point two"}]}];

const result = data.map((obj, key) => {

  const { Title: title, Name: value } = obj;
  
  const children = obj.Children.map(obj => {
    const { Title: title, Name: value } = obj;
    return { title, value, key: (key + 1).toString() };
  });
  
  return { title, value, children };
   
});

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Your API response is JSON. All you need to do is:

var resp=JSON.parse(API response);
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