Home > OS >  Adding an array of properties to an object
Adding an array of properties to an object

Time:10-28

I have an array of student objects that has some basic information like Name and Address. I want to be able to add a tag property to the object that is based on the user's input
I am acomplishing this with an input like this

<input placeholder="new tag" onInput={(e) => setAddedTag(e.target.value)} /> 
<button type="submit" onClick={() => addTag()}>Add Tag</button>

And I am adding the tag property to the specific object with this code

const addTag = () => {
  setStudentIndex(students.id - 1)
  students[studentIndex].tag = [AddedTag]
  // needs to add more than 1 
}

However this seems to only work with one tag, and if the user adds a second tag it will overwrite the first one. (or it will just crash) I have tried using the spread operator

students[studentIndex].tag = [...AddedTag]

However this instead set the tag to be ['a', 'b', 'c'] when the user had typed in abc How can I accomplish adding an array of string as a prop?

CodePudding user response:

have you tried using push()? something like:

students[studentIndex].tag.push(AddedTag);

CodePudding user response:

define the tag to be an array within the object. Something like this:

const students = [
   {
       name: "xyz",
       address: "abc",
       tag: []
   }
]

Then in your code change the following line from: students[studentIndex].tag = [AddedTag] to students[studentIndex].tag.push(AddedTag)

That should do it.

CodePudding user response:

try

const { tag = [] } = students[studentIndex]
students[studentIndex].tag = [...tag, AddedTag]

CodePudding user response:

You can probably achieve what you want by using an object with keys corresponding to the student ID

  • Related