0

Just started learning hooks and came about this problem. I was trying to add the same property to each of the objects within an array as follow:

const array = [ { 'a': 1, 
                  'b': 2, 
                  'c': 3}, 

                { 'd': 4, 
                  'e': 5, 
                  'f': 6} ]

const [ example, setExample ] = useState(array)

The desired result is as follow:

const array = [ { 'a': 1, 
                  'b': 2, 
                  'c': 3, 
                  'g': 7}, 
                
                 { 'd': 4, 
                   'e': 5, 
                   'f': 6, 
                   'g': 7} ]

The function I wrote:

function addG () {
  let toBeAdded = { 'g' : 7 }
  let alteredArray = array.map((object) => {
    return {...object, toBeAdded}
  }
  return alteredArray
}

Then to invoke the function:

const [ example, setExample ] = useState(()=>{addG()})

It is not working haha Would love to be pointed out what I was doing wrong! Thanks in advance!

1 Answer 1

1

you need to deconstruct toBeAdded as well. Like so:

function addG () {
  let toBeAdded = { 'g' : 7 }
  let alteredArray = array.map((object) => {
    return {...object, ...toBeAdded}
  }
  return alteredArray
}
Sign up to request clarification or add additional context in comments.

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.