Extracting JSON data and assigning it to a variable in JavaScript

I'm facing an issue dealing with a JSON array. I have a name that provides me with the following formatted code:

nanorep.floatingWidget.$refs.core.conversationSession.entries
    (11) [a, a, a, 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: 1529495789458, html: "", text: ""}
    ...

Do you know how to extract the text from `nanorep.floatingWidget.$refs.core.conversationSession.entries[2].text` up to `nanorep.floatingWidget.$refs.core.conversationSession.entries[12].text`? Additionally, I need to handle scenarios where the length of the array varies. Sometimes there will be 10 or even 2 data blocks present. I want to create a variable containing all the text from `nanorep.floatingWidget.$refs.core.conversationSession.entries[all lengths].text`, in plain text format with spaces between them.

I attempted this approach since I have intermediate knowledge in Javascript and JSON. Here's my code snippet, any improvements would be appreciated:

var i=2;
var history = nanorep.floatingWidget.$refs.core.conversationSession.entries.length;
while (i<history) {
    printObject(nanorep.floatingWidget.$refs.core.conversationSession.entries[i].text);
}

After solving one problem, I encountered another challenge—converting dots to new lines. The converted string appeared as follows:

jeg vil si opp avtalen min med fjellinjen hvordan gjør det,Husk å ta brikken ut av bilen [...] 
hvordan får jeg tilbake depositumet på bombrikken,Du får tilbake depositumet når [...]

My issue lies in converting dots to new lines using:

chatHistory2 = historyText.toString();

chatHistory = chatHistory2.replace(/./gi, /<br>/); and

chatHistory = chatHistory2.replace(/./gi, /\n/);

I haven't been successful with these attempts. How can I correctly make each dot result in a new line?

Answer №1

If you want to extract a specific range of values from an array and then loop through them, you can use the following methods:


var array = nanorep.floatingWidget.$refs.core.conversationSession.entries;

array
    .slice(2, 12)
    .forEach(({ text }) => {
        console.log(text);
    });

To extract the desired property values, you can map the result using text.

var array = nanorep.floatingWidget.$refs.core.conversationSession.entries,
    chatHistory = array.slice(2, 12).map(({ text }) => text);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

5 Steps to Share Your Local Server with the World

Seeking assistance! I have successfully retrieved sensor data from my Raspberry Pi through a RestAPI, but it is currently operating on a local server. I would like to make this data accessible on the web. I have attempted using NGROG and localTunnel, but t ...

Executing a DELETE request in EJS with the help of Mongoose

After successfully creating a RESTful API using Node, I decided to incorporate EJS for the HTML and CSS integration. GET and POST requests were easily implemented, but I hit a roadblock when trying to set up DELETE functionality. Below is the code snippet ...

Creating a structure that contains a dynamic array of nested structures

I am working with the following data structures: struct date { int year; int month; int day; }; struct person{ char name[64]; struct date birthday; }; struct aop { int max; struct person **data; }; Initially, I allocated m ...

What is the process for sending a JSON request?

Review the structure provided { "layer_id":"1Wn", "name":"Example Place", "latitude":"45.5037078163837", "longitude":"-122.622699737549", "span_longitude":"0.62", "extra":{ "description":"Portland", "url":"http://en.wikipedia.o ...

Troubleshooting: Angular 2 property binding animations not functioning as expected

I'm attempting to create a fade-in animation for a div element. Here is the code snippet: import { Component, trigger, state, style, transition, animate, keyframes, group } from '@angular/core'; @Component( ...

Ways to automatically style the child divs within a parent div

I'm trying to figure out how to float a parent div with child divs of different widths and heights while maximizing the use of space and not being affected by absolutely positioned elements. For reference, here's an example: http://jsfiddle.net ...

Tips for generating multiple HTML hyperlinks using a for loop in a Chrome extension

function createDropDown(){ const tree = document.createDocumentFragment(); const link = document.createElement('a'); for(let index = 0; index < urlList.length; index++){ link.appendChild(document.createTextNode(urlList[index])); ...

Displaying outcomes solely based on JSON upon choosing a filter

Goal I aim to only show results once their respective state is chosen. Currently, all results are displayed automatically upon page load. I prefer if nothing is shown initially. Only when a state is selected should the corresponding results appear. Bac ...

Resolving Nested Array Structure

In my code, there is a function named combined that iterates through an array of orders to find customers who have placed more than one order and combines them based on their name and address. It successfully combines two orders from the same customer, but ...

"Uh-oh! Encountered a new unexpected runtime error. Can't seem

While working on my portfolio in Next.js, I encountered an issue. I added a header to display on all pages by placing it in _app.js without making any changes to _document.js. Here is the error message: Unhandled Runtime Error Error: No router instance fo ...

Manipulating dynamic elements using jQuery

I am facing an issue with manipulating a dynamically created element using jquery fonticonpicker. Even though I have tried to modify the icon using the code below, it has not been successful as .icons-selector i is generated by the plugin itself. In the p ...

Lazy loading a React grid gallery as you scroll

Currently, I am utilizing React grid gallery to showcase images from this repository: https://github.com/benhowell/react-grid-gallery. However, I am encountering an issue with lazy loading when the user scrolls on the page. <Gallery images={this ...

Error while retrieving reference from mongoDB in NodeJS

I am currently working on a small website that needs to query my local mongodb. Everything works perfectly fine on localhost. That's why I decided to begin with NodeJS. While all JavaScript functions work seamlessly when run separately, I encounter a ...

The React Native app mysteriously crashes repeatedly without generating any error logs when using the same component multiple

Currently, I am developing in React Native app Version 0.70. Encountering a peculiar issue where the React Native app crashes without any error logs in the console. Below is the snippet of my code where most crashes seem to happen: import { ...

Decoding JSON in Golang with specified field names

Given the JSON below { "Jon": { "Age": 15 }, "Mary": { "Age": 17 } } How do I convert it into a Golang struct? Typically, the struct will look like this: type Person struct { Name string `json:??,string` Age int `j ...

Leveraging form.errors.as_json for enhanced parsing to generate HTTP responses in Django

As someone who is relatively new to both JSON and Django forms, I find myself wondering about the proper way to utilize Djagno's user_form.errors.as_json() function for transferring error messages to the client-side. Currently, my code looks like this ...

Is there a way to customize the color of the like button?

I'm trying to create a Twitter-like button with an icon that changes color. When the button is clicked, it successfully changes from gray to red. But now I'm stuck on how to make it switch back from red to gray. I am currently using javascript ...

Navigate using the confirmation box with a selection of "yes" or "no

Whenever a user leaves a JSP page, I want to prompt them with a confirmation message containing "You have unsaved changes. Do you want to leave without saving?" along with yes and no buttons. If the user clicks "ok", they will be redirected to the intended ...

Vue component not receiving the updated prop value from parent component

I am encountering a problem with my parent-child component setup. The issue arises when I pass a validation field as a prop from the parent to the child, but it doesn't update upon the first click of the submit button in the child component. To explai ...

Sorting array encountered an error

My code includes two variables, one for a list of song titles and another for the authors of those songs: var songTitles = ["Song Title 1", "Song Title 2", "Song Title 3"] On loading the view, I alphabetically sort the "songTitles" like this: override f ...