简体   繁体   中英

Looping through a JSON array and push the values into an array variable using node.js

I'm trying to create a chatbot in Dialogflow using node.js. The training phrases will come from a JSON file.

example JSON:

{
"Training_Phrases": ["How can I help you?", "How can I assist you today?"]
}

The Training phrases is being added on the intent created but the two phrases are merged in a single line instead of being two separate phrases. Here is the current code that I have. The inputPhrases obj is the JSON file:

          async function createIntent(inputPhrases)  { 
          
                const displayName = ('Intent: ' + intentName);

                 //create training phrases 
                const trainingPhrases_Parts = [inputPhrases];
                const trainingPhrases = [];

                  trainingPhrases_Parts.forEach(Phrases_Part => {
                   const part = {
                     text: Phrases_Part,
                   };

                    // Here we create a new training phrase for each provided part.
                   const trainingPhrase_con = {
                     parts: [part],
                    };

                    console.log(part);
                   trainingPhrases.push(trainingPhrase_con);

                  });

                //CONSTRUCT THE INTENT
                const intent = {
                   displayName: displayName,
                   trainingPhrases: trainingPhrases,
                   messages: [message], 
                   };
         
const emptyArray = [];

Training_Phrased.forEach((text)=>{emptyArray.push(text)})

Also from your current code, what you're trying to achieve is not to clear but at this point you are pushing the whole object into the array and not the property of the object "parts" which actually stores the array.

trainingPhrases.push(trainingPhrase_con);

This should be trainingPhrases.push(trainingPhrase_con.parts); If you're are trying to store the parts in the trainingPhrases array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM