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

271
Visualizações
JavaScript spread object as function params

I am trying to spread an object to use as the parameters of a function. I'm pretty sure I've seen this done, but I cant remember how. I know how to do this with an array, but I need to do it with an object. Also, I can't just turn the object into an array using Object.values(obj) since in some cases the order of the values won't match the order of the params.

function sum(x, y, z) {
    return x + y + z
}

obj = {x: 23, y: 52, z: 12}

sum(...obj)  // <--- WHAT DO I PUT HERE?

Using an array, I would just do:

function sum(x, y, z) {
    return x + y + z
}

arr = [23, 52, 12]

sum(...arr)

In python, this would be:

def sum(x, y, z):
    return x + y + z

dict = {'x': 23, 'y': 52, 'z': 12}

sum(**dict)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Also, I can't just turn the object into an array using Object.values(obj) since in some cases the order of the values won't match the order of the params.

If this is the case, then there's no way to do this without somehow enumerating the desired property order, or by changing the function signature.

function sum(x, y, z) {
    return x + y + z
}
// while this works, it's quite unusual - I don't recommend it
sum.params = ['x', 'y', 'z'];

const obj = {x: 23, y: 52, z: 12}

console.log(sum(...sum.params.map(param => obj[param])));

function sum({ x, y, z }) {
    return x + y + z
}

const obj = {x: 23, y: 52, z: 12}

console.log(sum(obj));

about 4 years ago · Juan Pablo Isaza Relatório

0

You can catch object fields by name as below

function sum({x,y}) {
    console.log(x + y);
}

obj = {
    x: 5,
    y: 10
}

sum(obj) // output: 15
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