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

85
Visualizações
Javascript spreading an object's properties array at specific index

Given a react hook and an object with array properties, I want to find a way to update the hook by using the spread operator at a specific properties index. Here is an example where I want to take the index 0 of the array in each property and spread it

const [{ a, b, c }, setState] = useState({ a : 'x', b : 'x', c : 'y' })

const temp = {
    a : ['x1', 'y1'],
    b : ['x2', 'y2'],
    c : ['x3', 'y3']
}

setState({...temp[0]})

/* Expected to be spread onto
*  setState({
*    a : 'x1',
*    b : 'x2',
*    c : 'x3'
*  })
*/

How would I achieve this? Am I looking at the wrong place to begin with by using the spread operator?

Things I have tried

  • Tried looking into .filter() but I was not able to make it work
  • Tried playing around with the [0] position and other syntaxes but with no success either
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can map over Object.entries and then convert the result to an object with Object.fromEntries.

const temp = {
    a : ['x1', 'y1'],
    b : ['x2', 'y2'],
    c : ['x3', 'y3']
}
let res = Object.fromEntries(Object.entries(temp).map(([k,[v]])=>[k, v]));
console.log(res);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can try like this:

const temp = {
    a : ['x1', 'y1'],
    b : ['x2', 'y2'],
    c : ['x3', 'y3']
};

let obj = {};
Object.keys(temp).forEach(k=> obj[k] = temp[k][0]);

console.log(obj);

about 4 years ago · Juan Pablo Isaza Relatório

0

I don't know how to use the spread operator to do what you want, but you can accomplish this with reduce, something like

const temp = {
    a : ['x1', 'y1'],
    b : ['x2', 'y2'],
    c : ['x3', 'y3']
};

const indexToGrab = 0;

const newState = Object.entries(temp).reduce((acc, currentEntry) => {
    acc[currentEntry[0]] = currentEntry[1][indexToGrab];
    return acc;
}, {});
//{a: 'x1', b: 'x2', c: 'x3'}

setState(newState);
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