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

256
Visualizações
How to create a Javascript object from an array of known keys, but with the values initialized to null?

I have a JS object from which I will extract an array of keys (using Object.keys()) and then I want to use those same keys to create a different object, but this time with its values initialized to null.

In Python, I would do something like:

list_of_keys = ["key_1", "key_2"]

# The * unpacks the list, could be thought as a JS spread operator
new_dict = dict.fromkeys(*list_of_keys)

And I would retrieve a new dictionary with all its values initialized to None as a default.

I don't seem to find a similar property or method in Javascript, however.

EDIT: If using ESLint, @CerebralFart answer (the for... of...) might trigger a complaint from the linter. It can be addressed here.

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

0

You can use reduce method to do it:

const object = { key_1: 'value_1', key_2: 'value_2', key_3: 'value_3' };

const new_object = Object.keys(object).reduce((accumulator, currentValue)=> {
  accumulator[currentValue] = null;
  return accumulator;
}, {});

console.log(new_object)

about 4 years ago · Juan Pablo Isaza Relatório

0

There's no need to make this more complicated than a simple for loop:

const object = { key_1: 'value_1', key_2: 'value_2', key_3: 'value_3' };
const newObject = {};

for (const key in object) {
  newObject[key] = null
}

console.log(newObject);

Or, if you only have the keys

const keys = ['key_1', 'key_2', 'key_3'];
const newObject = {};

for (const key of keys) {
  newObject[key] = null
}

console.log(newObject);

ETA: You could also use Object.fromEntries with some mapping. Depending on what you want to do with the object, this may be marginally faster.

const object = { key_1: 'value_1', key_2: 'value_2', key_3: 'value_3' };

const newObject = Object.fromEntries(Object.keys(object).map(key => [key, null]));

console.log(newObject);

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