Using a Javascript Function to Transform Raw JSON Data into a Facebook Standard Event

Currently working on creating a custom JavaScript function to convert the JSON formatted track event into the corresponding Facebook Pixel event.

The track event is placed on an e-commerce site as shown below:

analytics.track('Product List Viewed', {
  category: 'Deals',
  list_id: 'hot_deals_1',
  products: [
    {
      category: 'Games',
      image_url: 'https://www.example.com/product/path.jpg',
      name: 'Monopoly: 3rd Edition',
      position: 1,
      price: 19,
      product_id: '507f1f77bcf86cd799439011',
      sku: '45790-32',
      url: 'https://www.example.com/product/path'
    },
    {
      category: 'Games',
      name: 'Uno Card Game',
      position: 2,
      price: 3,
      product_id: '505bd76785ebb509fc183733',
      sku: '46493-32'
    }
  ]
});

The JavaScript event described above is implemented on a website to gather details about a user's viewed Product List. The raw JSON message of the event is sent as follows:

{
  "anonymousId": "70bbe85a-97db-49da-b36f-419dd858f3be",
  "context": {
    "ip": "12.179.173.270",
    "library": {
      "name": "analytics.js",
      "version": "3.8.2"
    },
    "page": {
      "title": "Toys R Us",
      "url": "https://toys-r-us.com"
    },
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36"
  },
  "event": "Product List Viewed",
  "integrations": {},
  "messageId": "ajs-515fef4d8615e8f95d88988d0cb77e60",
  "originalTimestamp": "2019-06-18T17:16:11.546Z",
  "properties": {
    "category": "Deals",
    "list_id": "hot_deals_1",
    "products": [
      {
        "category": "Games",
        "name": "Monopoly: 3rd Edition",
        "position": 1,
        "price": 19,
        "product_id": "507f1f77bcf86cd799439011",
        "sku": "45790-32",
        "url": "https://www.example.com/product/path"
      },
      {
        "category": "Games",
        "name": "Uno Card Game",
        "position": 2,
        "price": 3,
        "product_id": "505bd76785ebb509fc183733",
        "sku": "46493-32"
      }
    ]
  },
  "receivedAt": "2019-06-18T17:16:11.579Z",
  "sentAt": "2019-06-18T17:16:11.554Z",
  "timestamp": "2019-06-18T17:16:11.571Z",
  "type": "track"
}

I am in the process of developing a JavaScript function to transform the raw JSON data into Facebook's fbq('track') function, converting the event into the equivalent ViewContent standard event on Facebook.

The expected output should resemble the following example, but I require assistance with constructing the JavaScript function to convert the JSON data into the desired format:

<script>
fbq('track', 'ViewContent', {content_name: ‘Monopoly: 3rd Edition’,
  content_category: ‘Games’,
  content_ids: ['45790-32'],
  content_type: 'product',
  value: 19,
  currency: 'USD'
 },
{
  content_name: ‘Uno Card Game’,
  content_category: ‘Games’,
  content_ids: ['46493-32'],
  content_type: 'product',
  value: 3,
  currency: 'USD'
 }
);
</script>

Answer №1

For the next attempt, take some time to experiment yourself and indicate where you faced challenges.

Below is an illustration of entering data in line with the fbq event settings.

<script>
  
  const data = {
    // ....
    // ....
    properties: {
      category: "Deals",
      list_id: "hot_deals_1",
      products: [
        {
          category: "Games",
          name: "Monopoly: 3rd Edition",
          position: 1,
          price: 19,
          product_id: "507f1f77bcf86cd799439011",
          sku: "45790-32",
          url: "https://www.example.com/product/path"
        },
        {
          category: "Games",
          name: "Uno Card Game",
          position: 2,
          price: 3,
          product_id: "505bd76785ebb509fc183733",
          sku: "46493-32"
        }
      ]
    }
    // ....
    // ....
  }
  
  const modifiedData = data.properties.products.map(({category, sku, price}) => ({
    content_category: category,
    content_ids: [sku],
    content_type: 'product',
    value: price,
    currency: 'USD'
  }));
   
  console.log(modifiedData)

  //fbq('track', 'ViewContent', modifiedData);
  
  </script>

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

Strange behavior noticed in the app.get() method of Node.js Express

Seeking clarification regarding the behavior of app.get() in Express. It appears that the function is not triggered when the path includes .html at the end. In the code snippet provided, the console logs "test" if attempting to access /random/example, bu ...

Discover the secrets to dynamically swapping out all columns in a Data Table with Angular2+

Whenever changes or events occur outside of the Data Table, my requirement is to replace all the columns. When the data table is displayed for the first time, it shows selected columns based on an event. However, if I select another option, the new column ...

If the user is not authenticated, Node.js will redirect them to the login page

I've integrated the node-login module for user login on my website. Once a user logs in, the dashboard.html page is rendered: app.get('/', function(req, res){ // Check if the user's credentials are stored in a cookie // if (req.coo ...

The function is unable to accurately retrieve the state value

In my app, I have a component where I'm attempting to incorporate infinite scroll functionality based on a tutorial found here. export const MainJobs = () => { const [items, setItems] = useState([]); const [ind, setInd] = useState(1); const ...

An issue arises when ReactRouter's useLocation is utilized, causing React to throw

https://i.sstatic.net/MtoLc.png Encountering an issue with useContext while utilizing the React Router useLocation hook. Attempting to retrieve information about the current page location using useLocation, but receiving the following error: useContext ...

Can you clarify the dissimilarity between `knex().select("id").from("users")` and `knex("users").select("id")` in Knex?

I have successfully connected knex with mysql and am working on a login form linked to a mysql database. Currently, I am performing a login check and I'm curious if there is any distinction between the following two queries: knex().select("id").from( ...

`Python automation for seamless HTTP browsing and HTML document generation`

My weekly routine at work involves printing out Account analysis and Account Positions for more than 50 accounts every Monday. I have to navigate through the page, select "account analysis", input the account name, format the page for printing, print the o ...

Modifying the appearance of one specific element within a loop

This may seem confusing, but it's a serious question. I am using PHP to loop through table rows and display them inside a table tag using AJAX. Each row has an ID called productTableRow. What I want to achieve is when a specific row in this table i ...

Is there a way to divide the array based on a specific letter in the alphabet using Angular?

I am trying to create something similar to this: "ABCDEF", "GHIJK", "LMNO", "PRSTU", "VYZXWQ", "0123456789" I have a list in alphabetical order; I want names starting with "ABCDEF" to be in one a ...

Jquery Enhancement for Navigation

Recently, I have implemented a header and footer navigation on my website. The header navigation consists of 1 UL (unordered list), while the footer navigation comprises 5 ULs. My goal is to align the first child of each UL in the footer navigation with th ...

Report of transactions containing product name and customer email address

Looking for a method to create a PayPal report that includes both the Item name (or ID) and buyer's email address. This solution can involve using Google script or directly through the PayPal report engine. Appreciate any assistance! ...

Difficulty in accessing controller data in AngularJS with ng-repeat

I am trying to display comments using ng-repeat in a section, but I am having trouble accessing the data. Even after debugging, I cannot access the data without modifying the controller. I am new to Angular and prone to making mistakes. HTML / JS &apo ...

Integrate retrieved JSON data using Ajax into D3 visualizations

Could someone please guide me on how to incorporate fetched JSON data using Ajax into D3? I've integrated this example here into my project and now I just want to populate the radial layout with my own data. The image below shows the current bilevel r ...

Guidelines for accessing the value of the parent function upon clicking the button within the child function?

I have a pair of buttons labeled as ok and cancel. <div class="buttons-div"> <button class='cancel'>Cancel</button> <button class='ok'>Ok</button> </div> The functions I am working wi ...

Step-by-step guide on utilizing a for loop to print out each element of an array on the console

Currently, I am tackling an assignment that delves into experimenting with various loop types. In particular, I am tasked with using a for loop to output each item in the array named 'cars' utilizing console.log. It's essential to note that ...

Numeric Input Box: Show gaps

I have numeric input boxes in my HTML/PHP/JS application where users will be entering numbers with 4 to 7 digits. However, I want the users to see spaces between every third digit for better readability. For instance, User types: 8000 Us ...

Using regular expressions to replace all special characters, excluding dots

$('#price').keyup(function(){ $('#price').val($('#price').val().replace(/[_\W]+/g, "-")); }) Experience it firsthand here: http://jsfiddle.net/2KRHh/6/. In the scenario above, special characters are eliminated. ...

Having difficulties accessing the REST API functionality within Oracle Business Intelligence Publisher

I've been attempting to access a BIP report by calling the REST API services through the Postman tool. I have tried using various methods like GET, POST, PUT, and DELETE as outlined in the Oracle documentation to retrieve data from the server. However ...

"Time" for creating a date with just the year or the month and year

I am trying to convert a date string from the format "YYYYMMDD" to a different format using moment.js. Here is the code snippet I am using: import moment from 'moment'; getDateStr(date: string, format){ return moment(date, 'YYYYMMDD&a ...

What is the best way to combine key and value back into an object?

Within my Angular application, I am utilizing ng-repeat to iterate through all the elements in a JSON object. For instance, consider the following JSON structure: $scope.animals = { horse: { sound: "Nay", legs: 4, } bea ...