Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda