Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

reactjs - 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);
question from:https://stackoverflow.com/questions/65874894/iterating-through-database-object-and-append-data-to-object-with-a-certain-key-v

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...