0

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?

1
  • Kindly first search thoroughly about what you're looking for before asking question. Commented Nov 22, 2018 at 6:20

1 Answer 1

2

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 = [];
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Where will I set this state, as I'm setting up the initial state of students from an API call?
@Binny.H So, you meant: You want to get the response from server via using API that contains array property?
No, basically the initial state is being set from API call. Which I showed of example above. Then I want to add an empty array to each student object in that array so that I can push elements in that new array later.
@Binny.H I've updated the answer. Is it what you meant?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.