Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
Is there any way that I can add another value to a key in an object within React?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
      }
    })
  }
about 4 years ago · Juan Pablo Isaza Report

0

I think you can use approach like this:

updateTags = (key, tag) => 
    setTags((prevTags) => ({ 
        ...prevTags,
        [key]: prevTags[key] ? [prevTags[key], tag].flat() : tag,
    }));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!