0

I have an API call that returns an Object that contains a nested Array of Objects.

I want to add a property to all the Objects in Key3's array and set those values individually from another API call but i cant get it to work...

var object = {
    key1: "string",
    key2: bool,
    key3: [
        { key1: "Thing1", key2: value2, key3: value3 },
        { key1: "Thing2", key2: value2, key3: value3 },
        { key1: "Thing3", key2: value2, key3: value3 },
        { key1: "Thing4", key2: value2, key3: value3 },
        { key1: "Thing5", key2: value2, key3: value3 }
    ]
}

var array = object.key3;

for (var i = 0; i < array.length; i++) {
  axios.get(`https://api.callblahblablah${url[array[i].key1]}`)
    .then(response => {
  array.forEach(function(obj) { obj.key4 = response.data.result; }); 
//response.data.result is a float.
  this.setState({data: array})
          })
    .catch(err => console.log(err));
    }

}

The API call returns a specific value (float) that corresponds with a particular object, I want to match them up.

At the moment Key4 is added to each Object in array ok but its value is the same for every object.

I'm trying to match the correct value returned by each api call to its corresponding object. So the first api call adds the key-value pair returned to array[0], the second api call adds key4 and it's value array[1], the third api call adds key4 and the value returned to array[2] and so on and so forth.

I know it's something to do with the forEach.

4
  • Can you show what you tried and what is not working or where is the limitation in your code (due to Immutable) ? Commented Feb 23, 2018 at 11:55
  • Do you want to update each object depending on their "key" prop or index ? Commented Feb 23, 2018 at 11:58
  • Yes, you have to make a copy of that array. Update the objects inside it, and then setState again with the newly modified array. Commented Feb 23, 2018 at 12:39
  • Hi, thanks for the replies, I've edited my question a little to make it clearer. Commented Feb 23, 2018 at 16:59

1 Answer 1

1

.map() over your array in order to add your properties, then set your brand new array in the state with

this.setState(lastState => ({
    myObj: { ...lastState.myObj, key3: brandNewArray }
}));
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for the answer, I've edited my question a little to make it clearer.

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.