Matt Laszcz
Matt Laszcz

Reputation: 409

Iterating through database object and append data to object with a certain Key Value in Javascript

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);

Upvotes: 0

Views: 138

Answers (1)

Baryo
Baryo

Reputation: 324

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']  
  }
}

Upvotes: 1

Related Questions