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

149
Visualizações
how can i refactor this function using array destructuring?

Helo everybody,

I have build this function to convert the fetch data of an Api to an array of objects, but linters are requesting me to use array destructuring.

can jou please help me? im just a begginner so please be nice!

export const organiceData = async () => {
  const data = await getData();
  const toArr = Object.entries(data);
  let newBook;
  const arr = [];
  toArr.forEach((book) => {
    newBook = book;
    newBook[1][0].id = book[0];
    arr.push(newBook[1][0]);
  });
  return arr;
};

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Ignore that particular warning message. But still you should fix some things in your code:

  • use map instead of forEach+push
  • get rid of the useless newBook alias - assignment is not creating a copy, and certainly not a deep copy of the object
  • book is not actually a book object, it's a tuple (two-element array) representing a key-value pair. The book object is the value - or rather, it appears to be contained in the first element of the value which is itself an array.
export async function organiceData() {
  const data = await getData();
  return Object.entries(data).map(pair => {
    pair[1][0].id = pair[0];
    return pair[1][0];
  });
}

Now we could also use destructuring instead of the pair variable, same as doing const key = pair[0], value = pair[1];:

export async function organiceData() {
  const data = await getData();
  return Object.entries(data).map(([key, value]) => {
    value[0].id = key;
    return value[0];
  });
}

If you want to create a copy of the object before putting an id property on it, as to not mutate it, you can use spread syntax in an object literal. We may also further use destructuring on the value (like const book = value[0];):

export async function organiceData() {
  const data = await getData();
  return Object.entries(data).map(([key, [book]]) => {
    return {...book, id: key};
  });
}
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