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

177
Visualizações
Convert object containing objects to array containing objects

I have a JSON object that will sometimes be an object (a single instance) and sometimes be an array (multiple instances of the object). I need to write an if statement that basically says if this section of JSON is an object, wrap it in an array containing that single object, and if it's an array containing multiple objects, return that array. In either instance I'm returning an array containing either 1 or multiple objects. Here is what the JSON looks like when it is NOT an array.

"link": {
  "values": {
    "key1": "value1",
    ...
    "key8": "value8"
    },
  "key9": "value9"
  }

And it should look like this when it's an array:

"link": [{
  "values": {
    "key1": "value1",
    ...
    "key8": "value8",

    },
  "key9": "value9"
  }]

EDIT ----------------------------- This is what I've written so far that is producing the type error I'm experiencing.

  const isLinkArray = sections.values;
  isLinkArray.link = Array.isArray(isLinkArray.link) ? isLinkArray.link : [isLinkArray.link];

EDIT 2 ---------------------------

The final answer ended up being almost identical to Kinglish' answer, so I figured I would post it here. The issue I ran into was that the JSON right above 'link' was also an array and that was causing the typescript error.

  const sectionsWithLinkArray = sections.map((section) => {
      return {
        values: {
          ...section.values,
          link: !Array.isArray(section.values.link) ? [section.values.link] : section.values.link,
        },
      };
    }); 
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use Array.isArray to check, then convert

let data = {
  "link": {
    "values": {
      "key1": "value1",
      "key8": "value8"
    },
    "key9": "value9"
  }
}

data.link = Array.isArray(data.link) ? data.link : [data.link];
console.log(data)

about 4 years ago · Juan Pablo Isaza Relatório

0

This can be done by writing a simple function that checks if it's an array.

const returnArray = (value) => {
  if (Array.isArray(value) {
    return value;
  }
  return 
}
about 4 years ago · Juan Pablo Isaza Relatório

0

updated the answer of @Kinglish to typescript one because you cannot change types of defined value as it giving error for this either simply ignore the typescript or define types that simply accept link in object and array of object or just created new variable that expect a link in the array and wrap it inside data by simply doing this:

const data = {
  link: {
    values: {
      key1: 'value1',
      key8: 'value8',
    },
    key9: 'value9',
  },
};

// This is the type of data you can't change it by default and it doesn't expect array of object of `link`.
// const data: {
//   link: {
//     values: {
//       key1: string;
//       key8: string;
//     };
//     key9: string;
//   };
// };

const linkArray = { link: Array.isArray(data.link) ? data.link : [data.link] };

// Now this is the type of linkArray that expect array of object of `link`
// const linkArray: {
//   link: {
//     values: {
//       key1: string;
//       key8: string;
//     };
//     key9: string;
//   }[];
// };


console.log('data', data);
console.log('linkArray', linkArray);
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