0

I am using react JS and have the data stored in state on a Firebase database. I am trying to iterate through the posts array and attach input data i.e "answer": "this is the answer to the object with the key matching the id value passed into postAnswerHandler.

I am trying to use an if statement to say if the key matches the variable id then append the data to that object.

I am not able to get this if statement to work though.

 state = {
        posts: [{"key":"-MRp_IicTzCu5AineeBB",
                 "answer":"hhhh"},

                {"key":"-MRpgKN1bFHC3pUSGoqn",
                 "answer":"gd"},

                 {"key":"-MRpkG08WrtPyW2rVKPb",
                 "body":"post 3",
                 "title":"post 3", 
                  "type":"Credit"}]
    }
postAnswerHandler = ( answer,id ) => {
        
            const data = this.state.posts;
            for (var key in data) {
                
                if (key === id) {
                       *** APPEND DATA HERE***
                              }; 
                    var obj = data[key];
                    var obj_1 = JSON.stringify(obj);
                        
                            for (var prop in obj) {
                                if(obj.hasOwnProperty(prop)){
                                    
                   
                   }
                }
                
             }

            const postData = JSON.stringify(this.state.posts);
2
  • 1
    The fact that you called the variable 'key' doesn't make it the key. You have to iterate over the objects in the array, and get the value for each key. Something like for (obj of data) {if (obj['key'] === id) {}} Commented Jan 24, 2021 at 19:44
  • @whats_done_is awesome thanks this worked! makes total sense now looking at it as well. Now I think I can append the data to that specific object and use axios.put to send it to the database. Commented Jan 24, 2021 at 19:48

1 Answer 1

1

Your 'key' is actually the index of the array rather than the actual key you're looking for.

You should iterate over the objects in the array and compare each key called 'key' with the id you're looking for.

for (const obj of data) {
  if (obj['key'] === id) {
    // do something with obj['answer']  
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

yes makes sense I was assuming key was passed automatically and not iterating through the string value 'key' of keys.

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.