Home > OS >  Is there any way that I can add another value to a key in an object within React?
Is there any way that I can add another value to a key in an object within React?

Time:03-19

I will have a list of objects that are going to be entered by an input field. I have it working where it will create the list of objects, but when I try to add another value to one of the objects that already exist. It will just replace the previous value within it.

Current output when I console.log()

const [ tags, setTags ] = useState({
1: 'hello',
2: 'world',
3: 'goodbye'
})

My expected output if person 1 adds the tag 'testing'.

const [ tags, setTags ] = useState({
1: ['hello', 'testing'],
2: 'world',
3: 'goodbye'
})

The function that I have so far that is taking the value from the input. A is an id number and B is the new tag.

function updateTags(a, b){

  if(tags.hasOwnProperty(a)){
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: ????
      }
    })
  }else{
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: b
      }
    })
  }

If you need more information please let me know.

CodePudding user response:

I think this should work

function updateTags(a, b){

  if(tags.hasOwnProperty(a)){
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: Array.isArray(prevTags[a]) ? [...prevTags[a], b] : [prevTags[a], b]
      }
    })
  } else {
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: b
      }
    })
  }
  • Related