如何将键值添加到对象数组?我正在获取一个api,并希望从用户的输入添加值到特定的学生/人数组。假设我们点击第一个列表的输入,我们输入xyz,它应该添加一个标签:'xyz',然后如果我们添加abc,那么它必须是标签:['xyz', 'abc']。我是新手,所以如果有什么严重的问题请原谅我。
import React from "react";
import "./App.css";
export default class FetchRandomUser extends React.Component {
state = {
loading: true,
people: [],
input: '',
}
async componentDidMount() {
const url = "https://api.hatchways.io/assessment/students";
const response = await fetch(url);
const data = await response.json();
this.setState({ people: data.students, loading: false });
//
}
onChangeHandler(e) {
this.setState({
input: e.target.value,
})
}
render() {
if (this.state.loadin) {
return <div>loading...</div>;
}
if (!this.state.people.length) {
return <div>didnt get person...</div>;
}
const list = this.state.people.filter(person => this.state.input.toLowerCase() === '' || person.firstName.toLowerCase().includes(this.state.input.toLowerCase()) || person.lastName.toLowerCase().includes(this.state.input.toLowerCase()))
.map(person => (
<div key={person.id}>
<li>
{JSON.stringify(person.firstName)}
{JSON.stringify(person.lastName)}
{/*want to add newTag value for particular person in list */}
<input type="text" />
{/* and display it here */}
</li>
</div>
));
return (
<div>
<div className="example1">
{/* this input will search and filter person based on first and last name */}
<input value={this.state.input} type="text" onChange={this.onChangeHandler.bind(this)} />
<ul>{list}</ul>
</div>
</div>
)
}
}
如果我正确理解了你的问题,这是你可以向对象添加键值的方法之一:
var obj ={ a: 1, b: 2 };
obj.c = 5
console.log(obj);
output
Object { a: 1, b: 2, c: 5 }
因为您想要为特定的学生执行此操作,因此应该有一个先找到正确学生的逻辑。所以你需要循环遍历student数组
const data = [your array]
const updatedData = data.map(student =>{
if (student.id === person.id) {// you need to use the correct key names here
student = {... student,
tag: "xyz" // this xyz comes from you input, you need to adjust here
}
}
return student
})
之后,您可以呈现正确的数据。记住,我只写了如何一次更新数组。由于您正在使用react,因此需要应用此逻辑来更新状态。所以每次有更新时,也要更新状态