Binny.H
Binny.H

Reputation: 83

Add array to an object inside of an array in state

So say I have an array like so:

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

I would like to add an array to the first object so it looks like this.

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

How can I go about doing that without messing with initial state but only update it?

Upvotes: 0

Views: 65

Answers (1)

Tân
Tân

Reputation: 1

You can try to use these following ways:

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

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

After getting the response from server, you can add array property to each student object immediately:

Example:

var obj = {};

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

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

Upvotes: 2

Related Questions