Efficiently converting arrays to strings in JavaScript using mapping techniques

My goal is to retrieve data through AJAX without formatting it as JSON, so I took the initiative to encode it myself.

The data I am working with consists of client records: where the pound sign (#) separates the client records, the pipe sign (|) separates the fields within each record, and the carat sign (^) distinguishes the field name from its corresponding value.

This is a simplified representation of the data:

name^James|email^<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff8c90929a929e9693bf98929e9693d19c9092">[email protected]</a>#name^Bary|email^<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="583a392a21183a392a21763b3735">[email protected]</a>#...

Upon loading this data into Javascript, my objective is to format it into a 2-dimensional array similar to this:

clients = [
['name'=>'James','email'=>'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="61120e0c040c00080d21060c00080d4f020e0c">[email protected]</a>'],
['name'=>'Bary','email'=><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedcdfccc7fedcdfccc790ddd1d3">[email protected]</a>]
]

Alternatively, an object format could also be considered. What would be the most effective method to accomplish this?

Answer №1

Caution: It is not advisable to include special characters (|,^,#) in your keys or values. If you encounter them, consider encoding with JSON for a smoother process. I highly suggest using JSON to avoid any manual work.

If you opt not to allow (|,^,#) in your keys and values, you can utilize the javascript split function. A sample code snippet is shown below:

var output=[];
var clients = input.split("#");

for (var client in clients)
{
  var outputClient={}
  var clientProps = client.split('|');
  for (var propPair in clientProps)
  {
     var propPairVal = propPair.split('^');
     outputClient[propPairVal[0]] = propPairVal[1];  
  }
  output.push(outputClient);
}

Nevertheless, using JSON is strongly recommended for its flexibility and decreased likelihood of bugs.

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

Encountering difficulties reading data from a database in a Next.js/Firebase application

I am encountering a problem within a nextJS app that I developed on Firebase. In my realtime DB, I have some stored data that I want to read using a component. Below is my firebase/config.js file: import {initializeApp} from "firebase/app"; imp ...

HTML does not get rendered when an Ajax update occurs

<script> function fun() { $.getJSON($SCRIPT_ROOT + '/_add_numbers', {}, function(data) { $("#totalprofit").text(data.total); }); return false; } var interval = setInterval(fun, ...

I'm having trouble displaying the content of my list items within the div

In my code, I have a class called "ignicoes" that includes a list as one of its attributes. This list contains other attributes such as dispositivo, latitude, longitude, and more. My goal is to retrieve the contents of this list and display them within my ...

Tips for executing multiple queries using the find method with mongoose

Using my controller, I am querying the find method like this: Campaign.find({'setting.types':'views','ownerId':{$ne:userId},$where:"this.expected_views>this.views.length"}).exec().then(doc=>{ res.st ...

When trying to submit a form, encountering an `Uncaught ReferenceError` due to calling ajax within

Attempting to trigger an ajax function within a form in order to retrieve a value for the dropdown. mypython.py @app.route('/new_data', methods = ['POST', 'GET']) def new_data(): #Filter data and return the data(data_lis ...

Securing data in AngularJS $http.post requests: Best practices

While working on $http.post requests for my app's backend, I noticed a security issue. When inspecting the data using tools like firebug in Firefox, I can see all the information being sent. Is it possible for third parties to intercept this data? Th ...

Using System.Text.Json to serialize Record members

Recently, I've been working with self-referencing members in my records. Take a look: type Payload = { Id: Guid } member x.DerivedProperty = $"Derived Property using id: {x.Id}" While NewtonSoft.Json used to serialize this perfectly ...

Calculation of column sums in ASP.NET MVC DataTable

I am looking to calculate the sum of the "Total" column and display it in the footer of my table. <script> $(document).ready(function () { $("#orderTable").DataTable( { "ajax": { ...

Transform chosen images into a slideshow using Node.js and Angular JavaScript

I'm currently working on a project where I have an array of images being printed out in Angular, which I can select and download as a zip file. However, I now want to modify this functionality to create a slideshow instead. I've already imported ...

Encountering an issue with the v-carousel component from Vuetify: receiving a 'Cannot read property 't' of undefined' error message

Currently, I am trying to create an image carousel using Laravel along with Vue/Vuetify. The issue lies in the fact that the Vuetify v-carousel and v-carousel-item components are not rendering properly due to the error mentioned in the title. I have alrea ...

A guide on extracting and converting text into a JSON file using PHP

I am in need of extracting specific strings from a text file and converting them into a JSON format. The text file I am referring to is named data.txt. "5 minute input rate 134000 bits/sec, 164 packets/sec 5 minute output rate 1320000 bits/sec, 150 packe ...

Can anyone provide guidance on how to simulate a click on a JavaScript action for an iPhone?

I am attempting to trigger a click on a "javascript:void(0)" link so that I can retrieve HTML data within the script. Can someone advise me on how to achieve this without using illegal APIs like UITouchEvent, as I only work with NSUrl? Thank you in advan ...

Creating a Recursive Facebook Page Data Scraper using Selenium and Node.js

I am trying to iterate through an array of Facebook page IDs and retrieve the code from each event page. However, I am encountering a problem where I only get the code of the last page ID in the array repeated multiple times. For example, if there are 3 ID ...

Do not forget to implement Array.find when working with the useSWR hook in Next.js

I have the following code: const fetcher = (url: string) => axios.get(url).then((r) => r.data); const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000}) console.log(data.find(d => d.id === "123")) The API path is ...

Unable to display images - PhoneGap

I am experiencing an issue where images that are being dynamically added to my HTML display correctly in Firefox, but on all the Android devices I have tested, the images do not appear. Instead, a box with their alt text is shown. HTML: <div class="ui ...

Transform an angular1 javascript circular queue implementation for calculating rolling averages into typescript

I am currently in the process of migrating a project from Angular 1 to Angular 2. One of the key components is a chart that displays a moving average line, which requires the use of a circular queue with prototype methods like add, remove, and getAverage. ...

Leveraging TypeScript's declaration file

Greetings! I am currently facing an issue while utilizing a declaration file in my TypeScript project. Here is the declaration file that I am working with: // Type definitions for Dropzone 4.3.0 // Project: http://www.dropzonejs.com/ // Definitions ...

Button placed within a jade table cell

I'm struggling to make a button appear in each row of the table. I am new to working with Jade and Node.js, so I can't seem to figure out why it's not showing up. Here is my Jade file: html head body table.table.table(border='1 ...

The Vue.js 2 router seems to malfunction when triggered programmatically, yet it functions properly when used as a

index js file I tried using Vue Router programatically, but it was not working for me. After searching online, I found that everyone used this.$router.push(). import Vue from 'vue' import Router from 'vue-router' import HelloWorld fro ...

Creating an array of objects in Javascript by setting two different values as a range

Given an array of objects structured as follows: [{value: "a", start: 1950, end: 1954, description: "aaa"}, {value: "b", start: 1953, end: 1956, description: "bbb"}, {value: "c", start: 1960, end: 1962, des ...