Zapier - Generating Lists from Data Objects

Hey there, I would love to hear your thoughts on this.

Summary

I am seeking advice on how to extract multiple objects from an array using JavaScript and the Code by Zapier app. While I have successfully extracted data from the array's string using the .split() method and output a single object with mapped data, I'm struggling to create multiple objects and compile them into a new array.

The Script

// Here is what my inputData looks like:
inputData = INFO [ 'Name1', 'Surname1', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="255d5d5d5d654248444c490b464a48">[email protected]</a>', 'phone1', 'Name2', 'Surname2', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2abababab92b5bfb3bbbefcb1bdbf">[email protected]</a>', 'phone2', 'Name3', 'Surname3', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2953535353694e44484045074a4644">[email protected]</a>', 'phone3' ]

const participants = inputData.records.split(',')

let i = 0
// Find every fourth item in the array starting at index 0, which represents the participant's First Name
const getName = function(participants, i) {
  for (i; i < participants.length; i += 4 ) {
       let name = participants[i]

         return name
    }
  };
// Find every fourth item in the array starting at index 1, which represents the participant's Last Name
const getSurname = function(participants, i) {
  for ( let i = 1; i < participants.length; i += 4 ) {
       let surname = participants[i]

        return surname
    }
  };
// Find every fourth item in the array starting at index 2, which represents the participant's Email Address
const getEmail = function(participants, i) {
  for ( let i = 2; i < participants.length; i += 4 )  {
       let email = participants[i]

        return email
    }
  };

// Output an object inside an array with the key/value pairs as shown below
output = {participants: [
{
  first_name: getName(participants, i),
  last_name: getSurname(participants, i),
  email: getEmail(participants, i)
}
]};

Example Output:

participants:
   1:
     first_name: Name1
     last_name: Surname1
     email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2cacacacaf2d5dfd3dbde9cd1dddf">[email protected]</a>

Upon logging the output, it correctly displays that an object has been created:

{first_name: 'Name1', last_name: 'Surname1', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abd3d3d3d3ebccc6cac2c785c8c4c6">[email protected]</a>'}

My Challenge

I am facing difficulty in iterating through the inputData and presenting the records in the following format:

participants:
   1:
     first_name: Name1
     last_name: Surname1
     email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="740c0c0c0c341319151d185a171b19">[email protected]</a>
   2:
     first_name: Name2
     last_name: Surname2
     email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="433a3a3a3a03242e222a2f6d202c2e">[email protected]</a>
   3:
     first_name: Name3
     last_name: Surname3
     email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4bebebebe84a3a9a5ada8eaa7aba9">[email protected]</a>

When I use console.log() for each function's output, I get each record from the for loops. However, it does not output a record for each iteration. Why might this be happening?

Answer №1

After multiple attempts, I finally achieved the desired result in the following manner:

const players = inputData.records.split(',');
const totalPlayers = players.length;

// Setting up an iterator based on the length of the 'players' array
class Sequence {
    constructor( start = 0, end = Infinity, interval = 1 ) {
        this.start = start;
        this.end = end;
        this.interval = interval;
    }
    [Symbol.iterator]() {
        let count = 0;
        let nextIndex = this.start;
        return  {
            next: () => {
                if ( nextIndex <=                     this.end ) {
                    let result = { value: nextIndex,  done: false }
                    nextIndex += this.interval;
                    count++;
                    return result;
                }
                return { value: count, done: true };
            }
        }
    }
};

let rangeOfPlayers = new Sequence(0, totalPlayers - 4, 4);

// Creating an array from the generated Sequence to determine iteration count
const startingPoints = Array.from(rangeOfPlayers)

// Defining a function to generate 'player' objects using a specific formula
const playerData = function(array, index) {
  let firstName = players[index]
  let lastName = players[index+1]
  let email = players[index+2]
  return {name: firstName, surname: lastName, email: email}
};

// Initializing an empty array and populating it with data during each cycle
let playerRecords = []
const playerList = startingPoints.forEach(function(index){
  playerRecords.push(playerData(players, index))
});

                                
output = {playerRecords}

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

How come CSS styles are not being applied to forms in AngularJS?

When attempting to apply CSS styles to a form in order to indicate invalid input, I encountered an issue. Even after using the important tag, the styles did not change. I created a dynamic form from JSON and now need to validate it. Following a suggestion ...

Bring in various React components from separate files

I am struggling with using a component from another JS file in ReactJS. The error message "Header is not defined" keeps popping up. Just to clarify, I am working with ReactJS but without NodeJS involved. Here's the snippet of code causing the issue: ...

The mistake in npm install is when the console logs a bug that is notorious for causing npm to malfunction

After reading this article, I successfully installed Node.JS version 9.4.0. $brew install node $node -v $v0.12.7 Next, I ran npm install -g grunt-cli for testing. H ...

Modify the structure of the JSON string

My JSON string is structured like this: [ { "queryResult": { "A": "12-04-2014", "B": 1 } }, { "queryResult": { "A": "13-04-2014", "B": 2 } }, { "qu ...

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

Bidirectional data binding between an Angular component and its parent controller

I am currently facing an issue with an Angular component (vendor-filters) where I am trying to pass data to and from a parent controller. The goal is to create a filter based on mainInfo and update the parent controller with the filtered data. However, I a ...

What process is involved in implementing TCO (Tail Call Optimization) for a recursive anonymous function in ES5?

Is there a way to optimize an anonymous recursive function for tail call optimization, similar to how a named recursive function can be optimized? If such a method exists, please provide explanations on how to achieve it. Below is an example of a recursi ...

A comprehensive guide on retrieving data from API across several pages

Struggling with pulling data from an API using React and facing the challenge of retrieving more than one page of data. "info": { "count": 493, "pages": 25, "next": "https://rickandmortyapi.com/api/character/?pa ...

Easily integrating a JavaScript file into an HTML document when utilizing a NodeJS Express server

Currently in the process of developing a chat application, utilizing the Express server with NodeJS and AngularJS for client-side management. Encountering an issue when attempting to include /js/code.js in my html, as it cannot be found due to not being p ...

Obtain the current time for a specific user

I'm currently struggling with obtaining the accurate 'trusted' user time, in order to prevent any cheating through manipulation of their computer's clock. Whether I utilize a basic date object, moment timezone, or even Google timezone ...

Adjust the values in a list using a "for loop"

Trying to limit the values within arrays led me to discover the useful function np.clip(). Although it achieved the desired outcome, I am puzzled by how it alters the array values in a list of arrays. Here is the code snippet in question: import numpy as ...

Loopback: Unable to access the 'find' property as it is undefined

I've come across a few similar questions, but none of the solutions seem to work for me. So, I decided to reach out for help. I'm facing an issue while trying to retrieve data from my database in order to select specific parts of it within my app ...

What is the method for avoiding short-circuit conditions in TypeScript?

Is there a way to evaluate conditions in TypeScript without using short-circuiting? TypeScript does not support & or | for boolean types. I need to avoid short-circuit checking because I call the showErrors function inside the isValueValid function. C ...

Retrieve information from the third section by utilizing ajax

My current setup involves: Having a form in form.php for inserting data, Displaying data in table format with pagination on display.php, and Using validation.js for validating form data along with the following function: $('#pagiCount a'). ...

Pikabu's Uphill Battle with Heights

I'm currently in the process of developing a new off canvas mobile menu for a website project to replace an outdated and faulty version. After some research, I have decided to use https://github.com/mobify/pikabu as it meets all my requirements. Howev ...

Honing in on JavaScript Media Queries within React

I have been attempting to incorporate the media query concept from a resource I found here in my React project. However, when testing the code snippet below, I encountered the following error: TypeError: isMobile.addListener is not a function function App ...

Property that is dynamically populated based on data retrieved from an external API

My template relies on an API call (Firebase) to determine the return value of my computed property, which in turn decides whether certain elements are displayed. However, I've noticed that my computed property is not reactive - its value in the templ ...

Execute Javascript after modification of the DOM

I have developed two custom directives known as app-content and app-content-item. These directives are intended to be utilized in upcoming projects to provide a basic structure with simple styling. They will be incorporated into a module and should be nest ...

Populate an HTML layout with MySQL information and dynamically add the content to the page using JavaScript

I'm facing a challenge with creating an about us page for a website. I am using a template to structure the page and I want to populate it with MySQL data. I have enclosed the entire <div> of the personcard within a <script> tag, but the p ...

Minimizing the frequency of getElementById calls for the same HTML element

When dealing with repetitive function calls using the same element as a parameter, is it more effective to store the element as a global variable? For instance, imagine a function that is triggered on every key press and takes an element as an argument. ...