简体   繁体   中英

Javascript - How to store result of the for loop into the variable?

This the data that I'm trying to parse, especially "text" value from the indexes:

(8) [a, a, a, a, a, a, a, a]
0:a {id: 2, articleId: "1156688772", type: 2, html: "<div id="DIV_1" style="box-sizing:border-box;color…ionUI.enableUserInput()    }</script></div></div>", text: "Fyll ut feltene under for å starte en chat: Alle f…tionSession.conversationUI.enableUserInput()    }"}
1:a {id: 3, type: 5, date: 1529671597923, html: "", text: ""}
2:a {id: 4, type: 1, html: "hvordan får jeg tak i en sånn bombrikke", text: "hvordan får jeg tak i en sånn bombrikke"}
3:a {id: 5, articleId: "1140973712", type: 2, html: "Gratulerer med ny bil! Velg den avtalen som passer for deg:", persistentOptions: Array(2), …}
4:a {id: 6, type: 1, html: "er det gratis med elbil", text: "er det gratis med elbil"}
5:a {id: 7, articleId: "1158440612", type: 2, html: "<p>El-biler passerer forel&oslash;pig gratis i&nbs…g i Norge,&nbsp;hvis man har AUTOPASS-avtale.</p>", text: "El-biler passerer foreløpig gratis i de fleste bomanlegg i Norge, hvis man har AUTOPASS-avtale."}
6:a {id: 8, type: 1, html: "a med dere", text: "a med dere"}
7:a {id: 9, articleId: "1158681852", type: 2, html: "<p>Jeg beklager, jeg forst&aring;r ikke sp&oslash;…. Kan du si det p&aring; en annen m&aring;te?</p>", text: "Jeg beklager, jeg forstår ikke spørsmålet ditt. Kan du si det på en annen måte?"}
length:8
__proto__
:Array(0)

I am trying to figure it out a best way to store a result of a for loop into variable to pass it to some HTML field. For Example I would like result of this code, which is giving me great results:

var chat = nanorep.floatingWidget.$refs.core.conversationSession.entries
var chatHistory = function() {
    for (var i=2; i<chat.length; i++){
        console.log(chat[i].text + ' ');
    }
}
chatHistory();

to be stored in the: var history = "result of above for loop" variable.

I was trying with the return instead of console.log, but without much success.

Is ran out of ideas, maybe anyone more experienced than me was facing similar issues in the past, and found a way to solve it?

Thanks for any kind of reply in advance.

You could map the values from index 2 and onwards and join each text. Or take the array without joining for later processing.

var chat = nanorep.floatingWidget.$refs.core.conversationSession.entries,
    chatHistory = function() {
        return chat.slice(2).map(({ text }) => text).join(' ');
    };

console.log(chatHistory());

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