简体   繁体   中英

Adding an array of properties to an object

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?

have you tried using push()? something like:

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

try

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

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.

您可能可以通过使用带有与学生 ID 对应的键的对象来实现您想要的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM