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

98
Visualizações
Conditionally assign from part of an object

I think there's an elegant way to do this (maybe using destructuring), but I'm stumped so far. I'd like to assign some of the keys and values from one object to another, conditionally based on a boolean.

function bigObject() {
  return { /* an object with lots of keys and values, lots */ }
} 

function myFunction(aBool) {
  // I want smallObject to be either empty or contain a subset of bigObject, based on aBool
  // here's where I am stuck
  let smallObject = aBool ? { keyA, keyB } = bigObject() : {};
}

JS complains that keyA is a reference error, and I can see how, even if I had this right, I'd just end up creating keyA and keyB variables, not smallObject as I want.

I know I can do this:

let smallObject = {};
if (aBool) {
  let bigObject = bigObject();
  smallObject.keyA = bigObject.keyA;
  smallObject.keyB = bigObject.keyB;
  smallObject.keyC = bigObject.keyC;
  // 5 of these
}

But that sure is a lot of stuff to write when I think there's a way I can write just the props names.

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

0

It's not a problem to use temporary destructuring variables. Just use them again to build the target object. If you want it in one expression, you can use an inline function that performs the destructuring in its parameter variables, and then returns the new object:

let smallObject = aBool ? (
    ({ keyA, keyB }) => ({ keyA, keyB })
) (bigObject()) : {};

const bigObject = () => ({ keyA: 1, keyB: 2, keyC: 3, keyD: 4});

let aBool = true;

let smallObject = aBool ? (
    ({ keyA, keyB }) => ({ keyA, keyB })
) (bigObject()) : {};

console.log(smallObject);

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use an IIFE that returns a destructured object.

const bigObject = {
  keyA: 'a',
  keyB: 'b',
  keyC: 'c',
};

const getObj = (aBool) =>
  aBool
    ? (({ keyA, keyB }) => ({ keyA, keyB }))(bigObject)
    : {};

console.log(getObj(true));

Or you could write your own "plucking" function to return a new object based on the original:

const bigObject = {
  keyA: 'a',
  keyB: 'b',
  keyC: 'c',
};

const pluck = (obj, callback) => callback(obj);

const getObj = (aBool) =>
  aBool
    ? pluck(bigObject, ({ keyA, keyB }) => ({ keyA, keyB }))
    : {};

console.log(getObj(true));

about 4 years ago · Juan Pablo Isaza Relatório

0

Option 1

if (aBool) smallObject = { ...smallObject, ...bigObject}; 

Option 2

if (aBool) {
   Object.entries(bigObject).forEach(([key, value]) => smallObject[key] = value);
}
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