attempting to employ the method of copying by converting result into a JSON string

Currently, I am utilizing the browser console to scrape and organize content with JS. Below is the code snippet:

This represents my result array

var arr = [
"George\nPresident & Founder",

"content",

 "Ronald\nCountry Director, America",

 "content",

 "Kriss, PhD\nVice President",

 "content",

 "Joseph, MS\nDirector",

 "content",

 "Elizabeth\nDevelopment Operations",

 "content",

 "Lisa, MFA, MBA\nU.S. Content",

 "content.",

 "Natalia\nCountry Director"
]

I have attempted the following:

  for(var i=0; len = result.length, i < len; i++){
    result[i]['something'] = [];
    if(i === 0){
        result[i].split('\n');
    }
    else if (i % 2 === 0) {
        result[i].split('\n');
    }
    console.log(result[i]);
    result[i]['test'].push(result[i]);

  }

The issue I am encountering is that result[i]['something'] = []; is undefined. However, when I console.log(result[i]), I receive the correct output. I have tried copying using JSON.stringify(result[i]), but only get one object back.

for(var i=0; len = result.length, i < len; i++){
    var arr = [];
    if(i === 0){
        result[i].split('\n');
    }
    else if (i % 2 === 0) {
        result[i].split('\n')
    }
    arr.push(result[i])
    // console.log(result[i]);
    console.log(arr);
  }

Unfortunately, this code does not split them; it merely pushes them into arrays.

When I console.log(result[i]), the output is as follows: (correct format, but not in strings or arrays, making it uncopyable)

George
President & Founder

 content 

  Ronald
  Country Director America 

  content 

  Kriss PhD
  Vice President 

  content 

  Joseph MS
  Director 

  content 

  Elizabeth
  Development Operations 

  content 

  Lisa MFA MBA
  U.S. Content 

  content

  Natalia
  Country Director 

Ultimately, I aim for the final result to resemble this:

var result = [
["George"],
["President & Founder"],

[ "content" ],

[ "Ronald"]
["Country Director, America" ],

[ "content" ],

[ "Kriss, PhD"],
["Vice President" ],

[ "content" ],

[ "Joseph, MS"],
["Director" ],

[ "content" ],

[ "Elizabeth"],
["Development Operations" ],

[ "content" ],

[ "Lisa, MFA, MBA"],
["U.S. Content" ],

[ "content." ],

[ "Natalia"],
["Country Director" ],
[ "content." ]
]

Any suggestions on how to achieve the desired result[i] for copying onto clipboard using copy(JSON.stringify(result))?

Answer №1

The responses from other contributors are quite interesting. I have a suggestion for a slightly longer solution that involves multiple for loops.

Here is the updated code:

UPDATE: I have made adjustments to ensure it works with the latest changes you made to your post.

function modifyArray(inputArray) {
    // create a temporary array
    let tempArray = [];
    
    // iterate through the input array
    for (let j = 0; j < inputArray.length; j++) {
        let splitString = inputArray[j].split("\n");

        // splitString will contain an array of 2 strings

        // using ES6 spread operator to push each element into tempArray
        tempArray.push(...splitString);
    }
    
    // tempArray now holds the desired result
    return tempArray;
}

How to use:

modifyArray(arr);

/*
this will output:

=> [
    "George",
    "President & Founder",

    "content",

    "Ronald",
    "Country Director, America",

    "content",

    "Kriss, PhD",
    "Vice President",

    "content",

    "Joseph, MS",
    "Director",

    "content",

    "Elizabeth",
    "Development Operations",

    "content",

    "Lisa, MFA, MBA",
    "U.S. Content",

    "content",

    "Natalia",
    "Country Director",

    "content"
]

You can either store the function's result in a new variable called let outcome:

let outcome = modifyArray(arr);

Or assign the function's return value back to the original arr variable.

arr = modifyArray(arr);

Answer №2

To efficiently organize the data, I suggest creating an array of objects where each object represents a person with their respective information. By looping through the array and grouping information two rows at a time, you can easily store and access the details for each individual.

var arr = [
 "George\nPresident & Founder",
 "content",
 "Ronald\nCountry Director, America",
 "content",
 "Kriss, PhD\nVice President",
 "content",
 "Joseph, MS\nDirector",
 "content",
 "Elizabeth\nDevelopment Operations",
 "content",
 "Lisa, MFA, MBA\nU.S. Content",
 "content.",
 "Natalia\nCountry Director"
];

const result = [];
for (let i=0; i < arr.length; i+=2) {
 const nameParts = arr[i].split("\n");
 result.push({
   name: nameParts[0],
   title: nameParts[1],
   content: arr[i + 1]
 });
}

console.log(result);

Answer №3

consider replacing arr.push(result[i]) with the following alternative


if (i % 2 == 0) {
    arr.push( result[i].split('\n'));
}
else
{
   arr.push(["content"]);
}

Answer №4

One effective way to reach your objective is by utilizing the reduce method in a more streamlined manner, as illustrated below:

let arr = [
  "George\nPresident & Founder",
  "content",
  "Ronald\nCountry Director, America",
  "content",
  "Kriss, PhD\nVice President",
  "content",
  "Joseph, MS\nDirector",
  "content",
  "Elizabeth\nDevelopment Operations",
  "content",
  "Lisa, MFA, MBA\nU.S. Content",
  "content.",
  "Natalia\nCountry Director"
]
let result = arr.reduce((acc, str) => {
  str.split('\n').forEach(str => acc.push([str]));
  return acc;
}, [])
console.log(result)

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

Parsing JSON in Swift

I am attempting to parse this JSON data ["Items": <__NSSingleObjectArrayI 0x61000001ec20>( { AccountBalance = 0; AlphabetType = 3; Description = "\U0631\U06cc\U0648"; FullCode = "P_21_JIM_456_IR_25"; IRNumber ...

A Node.js function may not provide a response immediately due to a pending request

Here is a simple upload method using node.js and express.js: upload: function(req, res, next){ // Loop through each uploaded file async.each(req.files.upload, function(file, cb) { async.auto({ // Create new path and unique file ...

What is the best method in Python for efficiently calculating the sum of values in a 2D NumPy array?

Currently, I am handling opencv mats, which are numpy arrays that serve as image representations. Is there an optimal and pythonic method to calculate the sum of all x,y coordinates in a frame? frame[xpos][ypos][0] # Please note that each pixel has thr ...

AngularJS: default radio button selection

I'm currently working on creating a color configurator using AngularJS with radio buttons. Everything seems to be functioning properly - the data binds correctly, etc., but I'm encountering an issue setting the default color radio button as check ...

"Error: The functionality of finding places on Google Maps is not

I've encountered an issue while trying to integrate Google Maps into my Node application. The map is loading correctly and I'm able to retrieve my location. However, I am facing a problem with implementing the Google Places API code to allow user ...

Encountering this issue despite confirming the presence of data on the line before! What could be the missing piece here? Error: Unable to access property 'includes' of undefined

Here is the situation.. I'm retrieving data from a database and storing it in an array of objects. These objects represent articles. I am working on implementing a filter system based on categories. The objective is to apply a filter that checks for a ...

Here are steps for iterating through JSON encoded data in a database and displaying it:1. Connect to

I have created a PHP form that saves user-submitted field values in a MySQL database. The form is lengthy and subject to occasional changes. To handle this, I utilized the json_encode feature to store all the form data in the database. Now, my task is to r ...

A quicker method for deleting an element from an array based on its index

Last year, I posted this and now I feel there could be a simpler solution. I am looking to remove an item from an array based on its index. Even if the array contains duplicate values, I want to be able to remove the item by its index. Here is a common ex ...

Guide on sending an AJAX request for file upload to a Spring MVC controller

Hello, I am looking for assistance with setting up an AJAX call to send a file upload request to the controller in JavaScript. I have a dialog box where I am uploading a file, and I want to trigger the AJAX call upon clicking the upload button. If anyone h ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...

Dealing with errors in a cowboy websocket handler

I have a requirement to handle invalid JSON parsing while using jiffy in the cowboy websocket handler. Whether the JSON is valid or invalid, I need to send an appropriate message to websocket_info for responding to the client. Below is my implementation. ...

Creating a versatile "add new entry" form in Angular that appends a new record to the parent scope

In my Angular application setup, I have an "Edit Invitation" state where a single invitation is scoped. This invitation contains a list of guests controlled by a guestList controller and iterated over in the view. <div ng-controller="guestListCtrl as g ...

Embed a YouTube video within the product image gallery

Having trouble incorporating a YouTube video into my Product Image Gallery. Currently, the main product photo is a large image with thumbnails that change it. You can see an example on my website here. Whenever I attempt to add a video using the code below ...

Retrieve the variance between two arrays and store the additions in AddedList and the removals in RemovedList using typescript

I am still getting the hang of Typescript and I am trying to figure out the best solution for my issue. I have two arrays, A and B, and I need to identify the difference between them in relation to array A. The goal is to separate the elements that were ad ...

Generating examples of two models that are interdependent

In my Javascript form, I have implemented an AJAX POST request that successfully creates a new instance of a model called Component. Now, my goal is to allow users to input keywords for the Component model through the same form. To achieve this, I have al ...

Creating dynamic scroll animations for sidebar navigation in a single-page website with anchor links

I need help creating a seamless transition between anchor points on a single page, while keeping a fixed navigation menu that highlights the active section. As a novice, I am unsure how to incorporate "( document.body ).animate" or any other necessary code ...

Utilizing AJAX and setInterval Techniques for Efficient handling of window.location.hash

//Collecting AJAX links var ajaxLink = $("#logo, .navLink, .tableLink, .footerLink"); //Storing the recent state as null (because there is none yet) var recentState = null; //Initializing the page state based on the URL (bookmarking compatibility) window ...

Executing a function right away when it run is a trait of a React functional component

Having a fully functional React component with useState hooks, and an array containing five text input fields whose values are stored in the state within an array can be quite challenging. The main issue I am facing is that I need to update the inputfields ...

The Jquery click event is not triggering when clicked from a hyperlink reference

I have a specific HTML href in my code snippet: <a id="m_MC_hl6_8" class="no_loaderbox button_link inline_block " href="somelink" target="_self">link</a> Upon clicking this link, a waiting box is displayed on the page. However, I don't ...

Retrieving information stored in local storage from a different path using Vuex

Using the config panel route, I am fetching data and setting it to local storage using Vuex and StoreJS: const state = { message: [], // console.log(message); sec: 0, // other state }; const getters = { message: ( ...