Converting variable data into a JSON array format

Currently, I am in the process of setting up header bidding with Prebid. My approach involves loading the desired ads from a database using PHP and MySQL, followed by creating text variables in JavaScript with the PHP data.

The issue arises when I attempt to create the "adUnits" variable. While manually writing the content directly works fine, replicating the same process using JavaScript results in failure.

Here is the code that functions correctly:

var adUnits = [{
     code: '/123/468x60',
     mediaTypes: {
         banner: {
             sizes: [
                 [468, 60]
             ]
         }
     },
     bids: [{
         bidder: 'adserver',
         params: {
             networkId: 1234
         }
     }]
 }, {
     code: '/123/336x280',
     mediaTypes: {
         banner: {
             sizes: [
                 [336, 280],
                 [300, 250]
             ]
         }
     },
     bids: [{
         bidder: 'adserver',
         params: {
             networkId: 1234
         }
     }]
 }, {
     code: '/123/300x600',
     mediaTypes: {
         banner: {
             sizes: [
                 [300, 600],
                 [300, 250]
             ]
         }
     },
     bids: [{
         bidder: 'adserver',
         params: {
             networkId: 1234
         }
     }]
 }];

And here is the code that isn't working:

var arrayadsname = adsname.split('#'); // Content of arrayadsname => /123/468x60#/123/336x280#/123/300x600
var arrayadssize = adssize.split('#'); // Content of arrayadssize => 468x60#336,280|300,250#300,600|300,250
var arraysize = '';
var ad = '';
var adUnits = [];
var preadUnits = '';

for (var i = 0; i < arrayadsname.length; i++) {  
    var arraysizeparts = arrayadssize[i].split('|');

    for (var j = 0; j < arraysizeparts.length; j++) {
        if (j == 0) {
            arraysize = '[' + arraysizeparts[j] + ']';
        } else {
            arraysize = arraysize + ',' + '[' + arraysizeparts[j] + ']';
        }
    }

    ad = '{code: \'' + arrayadsname[i] + '\', mediaTypes: {banner: {sizes: ' + '[' + arraysize + ']' + '}}, bids: [{bidder: \'adserver\', params: {networkId: 1234}}]}';

    if (i == 0) preadUnits = ad;
    else preadUnits = preadUnits + ',' + ad;
}

// Result of ad => {code: '/123/468x60', mediaTypes: {banner: {sizes: [[468,60]] }}, bids: [{bidder: 'adserver', params: {networkId: 1234}}]}, {code: '/123/336x280', mediaTypes: {banner: {sizes: [[336,280],[300,250]]}}, bids: [{bidder: 'adserver', params: {networkId: 1234}}]}, {code: '/123/300x600', mediaTypes: {banner: {sizes: [[300,600],[300,250]]}}, bids: [{bidder: 'adserver', params: {networkId: 1234}}]}

adUnits = "[" + JSON.stringify(preadUnits) + "]";

I have attempted various combinations by declaring the variable adUnits as an object, array, and text, utilizing JSON.stringify, JSON.parse, and also declaring "arraysize" as an array and parsing it. However, I am unable to identify the root cause of the issue.

Upon checking the console, I noticed this error: "callee: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Arguments.invokeGetter".

Thank you in advance.

Answer №1

To begin, create an array of sizes for each item in the adssize. For example, transform '300,600|300,250' into [[300, 600], [300, 250]]. Next, use this array to construct the adUnits object by mapping the codes (split by #) and accessing the corresponding index in the sizes array:

const codes = '/123/468x60#/123/336x280#/123/300x600'.split('#');
const sizes = '468x60#336,280|300,250#300,600|300,250'
  .split('#')
  .map(
    // str is something like: '300,600|300,250'
    str => str.split('|').map(
      // substr is something like: '300,600'
      substr => substr.split(/[,x]/).map(Number)
    )
  );

const adUnits = codes.map((code, i) => ({
  code,
  mediaTypes: {
    banner: {
      sizes: sizes[i]
    }
  },
  bids: [{
     bidder: 'adserver',
     params: {
         networkId: 1234
     }
  }]
}));
console.log(adUnits);

If you need the output in JSON format instead of an object, you can use JSON.stringify after the construction:

const codes = '/123/468x60#/123/336x280#/123/300x600'.split('#');
const sizes = '468x60#336,280|300,250#300,600|300,250'
  .split('#')
  .map(
    // str is something like: '300,600|300,250'
    str => str.split('|').map(
      // substr is something like: '300,600'
      substr => substr.split(/[,x]/).map(Number)
    )
  );

const adUnits = codes.map((code, i) => ({
  code,
  mediaTypes: {
    banner: {
      sizes: sizes[i]
    }
  },
  bids: [{
     bidder: 'adserver',
     params: {
         networkId: 1234
     }
  }]
}));
console.log(JSON.stringify(adUnits, null, 2));

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

Express Vue Production Problem

I've been attempting to implement SSR in my Vue app, and to achieve this I've incorporated the vue-plugin-ssr extension. To run it with express, I created a new file named server.mjs containing the following code: import express from "expres ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

Pondering in AngularJS - what is the best way to alter the DOM during an AJAX call?

I'm completely new to AngularJS and trying to transition from a jQuery background. After reading through "Thinking in AngularJS if I have a jQuery background?" on Stack Overflow, I understand the concept but am struggling to implement it without depen ...

Firefox is mistakenly interpreting a pasted image from the clipboard as a string instead of a file, causing

I am facing an issue where I am attempting to extract images from a contenteditable div using the paste event. The code works perfectly in Chrome but does not function as expected in Firefox. I have implemented the following code: $(window).on("paste& ...

Preserving State in React Router Through Page Reload

I recently set up a react router in order to display my Navbar on all routes except the login page. To achieve this, I created a Layout component that ensures users are redirected back to the Login page if they are not authenticated. Currently, I'm st ...

Prevent User Access to Start Button During Browser Request Processing

I have buttons for starting and stopping a window service on a server. When I click on the start button, the service takes some time to start. During this time, I need to disable the start button on the client side. The same goes for the stop button. Even ...

When going through an array using jquery, only the final object is returned

I am diving into the world of jQuery and dealing with what seems to be a basic issue. <input type="text" name="text1" value=""></input> <input type="text" name="text2" value=""></input> <input type="text" name="text3" value=""&g ...

Issue: React-Firebase-Hooks failing to retrieve dataHaving trouble with React-F

I've been utilizing the React-Firebase-Hooks package in my project, but I'm encountering some difficulties with its usage. In the code snippet below, the user.data().username is displayed correctly. However, when I try to use it within useState, ...

Converting user inputs and dropdown selections into JSON format using PHP

I am looking to serialize inputs and selected options with JSON datatype in the table provided below: <form action="" method="post" id="formpiw" spellcheck="false" autocomplete="off"> <table id="tblpiw"> <tr id="trwil"> <t ...

Tips for changing between two texts within a button when clicked

Seeking a solution for toggling between two different texts inside a button when making an ajax call, with only one text displayed at a time. I'm facing difficulty in targeting the spans within the button specifically. Using 'this' as conte ...

Unable to load page redirection

I am experiencing an issue with this page not redirecting to the appropriate mobile or desktop page when accessed. Below is the code snippet in question: <html> <head> <title>Loading...</title> </head> < ...

From where does the require.js file originate?

Currently, I am learning Angular 2 from the tutorial available at https://github.com/pkaul/maven-typescript-example. Once I proceed with the 3rd step (mvn jetty:run), a runnable war folder is generated in the example-webapp/target directory. However, I ha ...

Encountering a issue while swapping the base address of a 2D array with a third variable

It appears that the objective of the programs is to switch the addresses stored in names[3] and names[40] using an auxiliary variable t, but I keep encountering an error. #include<conio.h> #include<stdio.h> int main() { char names[5][20] = ...

Removing chips in Material UI can be easily accomplished by following these steps

Recently, I implemented a feature where chips are generated as the user types in a text field and clicks on create. A chip is then displayed with the entered text. Now, I am looking to add the ability to delete these chips dynamically. You can view the s ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Sophisticated method in JavaScript to conceal and reveal div elements

My knowledge of front-end web development is strongest in HTML and CSS, but when it comes to JavaScript, I feel like there must be a more efficient way to achieve the functionality I want. On my website, I have a set of <li> items that, when clicked ...

Create a chronological timeline based on data from a JSON object

Here is a JSON object generated by the backend: { "step1": { "approved": true, "approvalTime": "10-11-2021", "title": "title 1", "description": "description 1" ...

Interact with a React dropdown using SeleniumBase

I am having trouble testing a dropdown on a webpage I built with React and the Ant Design framework. I am attempting to use SeleniumBase or Selenium Webdriver for the task. The dropdown in question can be viewed here: https://ant.design/components/select/ ...

Can you explain the significance of 1e9 in the context of NodeJS hrtime?

When the calculation multiplies by 1e9 and divides by 1e6, what is the significance of this operation? ...

Challenges with Loading Picasso Images in Recycler View

Whenever I click on card view items, the images do not display even though the data is loaded correctly using JSON and Picasso. Can anyone help solve this issue with your expertise in the Picasso library? public class SeconActivity extends Activity { Re ...