2

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 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.