Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将数组添加到状态为的数组内的对象_Javascript_Reactjs - Fatal编程技术网

Javascript 将数组添加到状态为的数组内的对象

Javascript 将数组添加到状态为的数组内的对象,javascript,reactjs,Javascript,Reactjs,假设我有这样一个数组: this.state = { students: [{ "company": "This", "firstName": "Randy", "id": "1", "lastName": "Orton", }, { "company": "That", "firstName": "Clark", "id": "2", "lastName": "K

假设我有这样一个数组:

this.state = {
  students: [{
      "company": "This", 
      "firstName": "Randy", 
      "id": "1", 
      "lastName": "Orton", 
    }, 
    {
      "company": "That", 
      "firstName": "Clark", 
      "id": "2", 
      "lastName": "Kent", 
    }]
}
我想向第一个对象添加一个数组,使其看起来像这样

this.state = {
      students: [{
          "company": "This", 
          "firstName": "Randy", 
          "id": "1", 
          "lastName": "Orton", 
          "array" : []
        }, 
        {
          "company": "That", 
          "firstName": "Clark", 
          "id": "2", 
          "lastName": "Kent", 
        }]
    }

如何在不影响初始状态的情况下进行操作,而只更新初始状态?

您可以尝试使用以下方法:

this.state.students[0].array = [];

this.state.students.find(x => x.company === 'This').array = [];

从服务器获得响应后,您可以立即向每个
student
对象添加
array
属性:

例如:

var obj = {};

$.ajax({
    type: 'POST',
    url: '/yourAPIUrl'
}).done(function (response) {
    obj.state = reponse;

    for (var student of obj.state.students) {
        student.array = [];
    }
});

您可以尝试使用以下方法:

this.state.students[0].array = [];

this.state.students.find(x => x.company === 'This').array = [];

从服务器获得响应后,您可以立即向每个
student
对象添加
array
属性:

例如:

var obj = {};

$.ajax({
    type: 'POST',
    url: '/yourAPIUrl'
}).done(function (response) {
    obj.state = reponse;

    for (var student of obj.state.students) {
        student.array = [];
    }
});

当我通过API调用设置学生的初始状态时,我将在何处设置此状态?@Binny.H那么,您的意思是:您希望通过使用包含
array
属性的API从服务器获取响应?不,基本上初始状态是通过API调用设置的。我在上面展示了一个例子。然后我想向该数组中的每个学生对象添加一个空数组,以便以后可以将元素推送到新数组中。@Binny.H我已经更新了答案。这是你的意思吗?当我通过API调用设置学生的初始状态时,我将在哪里设置此状态?@Binny.H因此,你的意思是:你想通过使用包含
数组
属性的API从服务器获取响应?不,基本上初始状态是通过API调用设置的。我在上面展示了一个例子。然后我想向该数组中的每个学生对象添加一个空数组,以便以后可以将元素推送到新数组中。@Binny.H我已经更新了答案。这是你的意思吗?在提问之前,请先彻底搜索你要找的东西。在提问之前,请先彻底搜索你要找的东西。