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

146
Visualizações
Best approach in extracting the values of array inside object in js

What is best approach in extracting the below object. I tried two ways. Can this be refactored in any other way to optimize the performance?

const data = {
    "postcode": [
        "123456"
    ],
    "time": [
        "05:11"
    ]
};

Approach 1:

for (const element of Object.entries(data)) {
    const key = element[0];
    const value = element[1][0];
    data[key] = value;
}

Approach 2:

for (const key in data) {
    if (Object.hasOwnProperty.call(data, key)) {
        data[key] = data[key][0];
    }
}

console.log('data ', data);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

A concise method is this:

for (const [key, [value]] of Object.entries(data)) {
    data[key] = value
}

Notice the extra set of [] around [value] to extract the value from that array immediately too.

Of course, conciseness isn't always better and you may prefer your other solutions if you think they are more readable.

In terms of performance this isn't any better than your first solution. Your second option will be more memory efficient though it heavily depends on the size and shape of your object.

about 4 years ago · Juan Pablo Isaza Relatório

0

This approach will solve your problem. MDN recommended!

const object1 = {
  a: 'somestring',
  b: 42
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"
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