Javascript spreading an object's properties array at specific index

Viewed 110

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
3 Answers

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);

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);

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);
Related