jipster96
jipster96

Reputation: 3

Add properties to objects within an array with React Hooks

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!

Upvotes: 0

Views: 707

Answers (1)

Iosif
Iosif

Reputation: 822

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
}

Upvotes: 1

Related Questions