JSX Script issue: the input prompt is missing

Greetings! I am currently working on a script to export JSON files from Adobe Illustrator.

// Custom function for exporting prefixed objects
function exportPrefixedObjects(doc) {
  // User input for prefixes and reference points
  var prefixInput = prompt("Enter the Prefixes separated by commas","btn_,dlg_");
  var referencePointInput = prompt("Enter the reference point for each prefix separated by commas","center,top_left");
  var prefixes = {}
  var prefixArr = prefixInput.split(',')
  var referenceArr = referencePointInput.split(',')
  
  for(var i=0; i<prefixArr.length; i++){
      prefixes[prefixArr[i]] = referenceArr[i]
  }

  const prefixedObjects = [];
  for (var i = 0; i < doc.layers.length; i++) {
    const layer = doc.layers[i];
    const name = layer.name;

    // Checking if the layer name starts with a prefix
    for (var prefix in prefixes) {
      if (name.startsWith(prefix)) {
        // Obtaining the reference point
        const referencePoint = prefixes[prefix];

        // Getting the position of the layer
        const pos = layer.position;

        // Retrieving the width and height of the layer
        const width = layer.width;
        const height = layer.height;

        // Creating an object with the layer's information
        const obj = {
          name: name,
          x: pos[0],
          y: pos[1],
          referencePoint: referencePoint,
          width: width,
          height: height
        };
        prefixedObjects.push(obj);
        break;
      }
    }
  }
  return prefixedObjects;
}

// Custom function to obtain artboard information
function getArtboardInfo(artboard) {
  return {
    name: artboard.name,
    origin: {
      x: artboard.rulerOrigin[0],
      y: artboard.rulerOrigin[1]
    }
  };
}

// Accessing the active document and selected artboard
const doc = app.activeDocument;
const selectedArtboard = doc.artboards[doc.artboards.getActiveArtboardIndex()];

// Fetching the array of prefixed objects and their respective details
const prefixedObjects = exportPrefixedObjects(doc);

// Retrieving the artboard information
const artboardInfo = getArtboardInfo(selectedArtboard);

// Adding the artboard info to each prefixed object
prefixedObjects.forEach(obj => {
  obj.artboardName = artboardInfo.name;
  obj.artboardOrigin = artboardInfo.origin;
});

// Converting array of objects into a JSON string
const jsonString = JSON.stringify(prefixedObjects);

// Saving the JSON file
const file = new File(doc.path + '/prefixed-objects.json');
file.open('w');
file.write(jsonString);
file.close();

The issue at hand is that the prompt() function is not appearing, resulting in an error. Upon investigation, it was discovered that

the prefixedObjects

array does not contain any values (which makes sense as there is no input provided).

I'm unsure how to proceed from this point.

Answer №1

Illustrator's Extendscript is like the vintage version of Javascript, harking back to the days of ES3 or ES4. It lacks modern functionalities such as forEach, map, and filter array methods. This means you'll need to opt for a more traditional approach when manipulating arrays:

prefixedObjects.forEach(obj => {
  obj.artboardName = artboardInfo.name;
  obj.artboardOrigin = artboardInfo.origin;
});

One workaround is to use a classic loop structure, such as a 'for' loop:

for (var i=0; i<prefixedObjects.length; i++) {
  var obj = prefixedObjects[i];
  obj.artboardName = artboardInfo.name;
  obj.artboardOrigin = artboardInfo.origin;
}

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

Does CausesValidation validate all validators, including validation groups?

I have encountered an issue with my web page where I have 3 separate validation groups, but when I attempt to submit the form, I want all of the groups to validate simultaneously. It appears that using causesValidation="true" on the button does not trigge ...

A guide on adding a JSON object to an array in R

I have attempted various methods to insert a JSON object into an array and save it in the same format as the example below, but unfortunately, I have not been successful. Does anyone have a solution to accomplish this in R? Thank you EDIT : I have foun ...

Preventing audio from being muted using JavaScript requires the removal of audio tags through a MutationObserver

I attempted to utilize the script below to eliminate all audio from a specific website: // ==UserScript== // @name addicto // @namespace nms // @include http://* // @include https://* // @version 1 // @grant none // ==/UserScrip ...

Strategies for enhancing the effectiveness of a try statement when repeatedly used in Python

I am currently working on extracting various elements from a JSON object that consists of metadata related to a specific song using Python. In order to verify the availability of information, I have implemented try-except statements for each metadata eleme ...

Utilizing arrays to populate a line graph in Highcharts

I am struggling to figure out how to incorporate data from an array obtained from another function in my javascript file into my line graph. I want to confirm that this is feasible without switching to a different graphing package. Below is my current co ...

What is the best method for opening .xls files using ExcelJS?

I am facing an issue with accessing a .xls file using the ExcelJS library. Interestingly, there are no issues when it comes to reading .xlsx files. Previously, I relied solely on the xlsx js library and never encountered any problems while accessing .xls f ...

Laravel and Vue: Retrieve complex data with multiple relationships

In my data model, I have a concept of Exercise which is linked to Topic, and Topic is associated with Subject. By using the code snippet below: Exercise::with('topic')->get() I can easily access the properties of the current topic within Vu ...

Recursive routing in NodeJS using Express

Certain website APIs have the capability to perform actions such as: Initial user's id their first friend, also a user v v GET /api/users/54282/friends/0/friends/0 ...

Text below a stationary header

I need some help with my code using material-ui-next beta.30. The issue I am facing is that the content within mui.Paper is appearing behind the AppBar instead of below it. Here's my current setup: import * as React from 'react'; import * a ...

Converting a JSON file embedded in pandas python to a CSV format

Hey there! I recently received a JSON file with the following format. Can you guide me on how to parse this JSON file and convert it into CSV? JSON File Format {'Sections': [{'MC': [[{'IsMandatory': False, 'LD&apo ...

Function invoking React Hook

I'm a beginner to React JS and I've been learning by working on a project. I was creating a basic e-commerce UI with items and attempting to add items to a cart, but encountered an issue. The React Hook "useStateValue" is being called in the fun ...

Avoiding GulpJs freezing with effective error handling techniques

I am currently in the process of converting my sass files to css and encountering some issues. Specifically, I am struggling with handling errors during the sass conversion process. Whenever there is an error, it causes gulp to hang, requiring me to rest ...

Why do `setTimeout` calls within JavaScript `for` loops often result in failure?

Can you help me understand a concept? I'm not inquiring about fixing the code below. I already know that using the let keyword or an iffe can capture the value of i. What I need clarification on is how the value of i is accessed in this code snippet. ...

Having trouble setting the InnerHTML property of Null on my Ionic app, what could be the issue?

I'm working on a code to display the remaining time for generating a random code in the DOM. var count = setInterval(function () { var date = new Date(); var currentSecond = date.getSeconds(); ...

Issues with Ajax response being added to the table

I am encountering a technical problem with my university project. The task assigned by the professor is as follows: We need to create a static table that lists 3 domain names in order to enhance the performance of the domain availability API. <table&g ...

Issue with MUI Autocomplete not showing selected name on initial option selection

I encountered a strange issue with the Autocomplete component from Material UI. Here is the code snippet in question: const [isContactListInitialised, setContactListInitialised] = useState(false); const toggleContactListInitialized = () => { setContactL ...

What is the best way to ensure that only one div is toggled at a time while using the toggle class function?

$(document).ready(function(){ $("#items").children().click(function(){ $(this).toggleClass('clicked'); }); }); .clicked { background-color:red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></s ...

The collapse feature in react-bootstrap is malfunctioning

I've been experimenting with the Collapse feature from react-bootstrap in order to implement a collapsible table row. The goal is to have table rows that expand and collapse when clicked, revealing more information specific to that row. While it see ...

When the page loads, a JavaScript function is triggered

My switchDiv function in Javascript is being unexpectedly called when the page loads. It goes through each case in the switch statement, except for the default case. Does anyone know how to solve this issue? $(document).ready(function() { $("#be-button" ...

What is the best way to showcase the outcomes of a map function in JSX?

I'm currently learning react and working on implementing the searchMap function (to display movie title/poster) with the TMDB API. While I am able to successfully log the necessary information to the console, I am encountering issues such as undefined ...