简体   繁体   English

向对象添加属性数组

[英]Adding an array of properties to an object

I have an array of student objects that has some basic information like Name and Address.我有一组student对象,其中包含一些基本信息,如姓名和地址。 I want to be able to add a tag property to the object that is based on the user's input我希望能够向基于用户输入的对象添加tag属性
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我正在使用此代码将tag属性添加到特定对象

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?然而['a', 'b', 'c']当用户输入abc时,这反而将标签设置为['a', 'b', 'c']如何完成添加字符串数组作为道具?

have you tried using push()?你试过使用 push() 吗? something like:就像是:

students[studentIndex].tag.push(AddedTag);学生[学生索引].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)然后在您的代码中将以下行从: students[studentIndex].tag = [AddedTag]更改为students[studentIndex].tag.push(AddedTag)

That should do it.应该这样做。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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