Struggling to interpret the outcomes of an array

Having some difficulty parsing the results of an array and displaying them in the console. There are two issues at play here. First, when building the array, it seems to be adding "undefined" to the results. Second, when attempting to loop through the individual strings in the array, it's not parsing correctly and instead just returning the full array object.

The goal is to gather all the field values selected from a list view and write them to another child list as separate items. However, when the results are displayed in the console, they appear as an object array. Running the typeof method on it seems to indicate that it's being treated as a string.

In summary, why is "undefined" being included and why is the array not being printed to the console correctly? Below is an example of the current output (with two records selected) and the accompanying code:

Results:

undefinedDaffy DuckBugs Bunny

undefined

Code:

// Function to call when selected items are ready
function callAccepted() {
    getSelected().done(function(varObjects) { 
        for (var k in varObjects) {
            console.log(varObjects[k]);
        }
    });
}

// Function to get selected items from list view
function getSelected() {
    var dfd = $.Deferred(function(){
        var ctx = SP.ClientContext.get_current();
        var clientContext = new SP.ClientContext(); 
        var targetList = clientContext.get_web().get_lists().getByTitle(ListName);
        var SelectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
        var items = [];
        var arrItems = [];
        for (var i in SelectedItems) {
            var id = SelectedItems[i].id;
            var item = targetList.getItemById(id);
            clientContext.load(item, "Title");
            items.push(item);
        }
        clientContext.executeQueryAsync(
            function(){
                var itemLength = 0;
                var itemObjects = [];
                for (var j = 0; j < items.length; j++) {
                    itemObjects = items[j].get_item("Title");
                    itemLength += itemObjects;
                    arrItems.push(itemObjects);
                }
                dfd.resolve(arrItems, itemLength);
            },
            function(){
                dfd.reject(args.get_message());
            }
        );
    });
    return dfd.promise();
}

Answer №1

Why do you have the line "var itemObjects;" and then add "itemObjects += items[j].get_item("Title");" in a separate line? Combining these two lines into one should resolve the issue of "undefined" appearing:

function callAccepted() {
    getSelected().done(function(varObjects, iLength) { 
    // Stuff
                for (var k = 0; k < iLength; k++) {
                        console.log(varObjects[k]);
                }
    }); // End getSelected
} // End callAccepted

// Function to retrieve user information
function getSelected() {
    var dfd = $.Deferred(function(){
        var ctx = SP.ClientContext.get_current();
        var clientContext = new SP.ClientContext(); 
        var targetList = clientContext.get_web().get_lists().getByTitle(ListName);
        var SelectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
        var items = [];
        var arrItems = [];
        for (var i in SelectedItems) {
            var id = SelectedItems[i].id;
            var item = targetList.getItemById(id);
            clientContext.load(item, "Title");
            items.push(item);
        } // End for
        clientContext.executeQueryAsync(
            function(){ // Return to button click function
                for (var j = 0; j < items.length; j++) {
                    var itemObjects = items[j].get_item("Title");
                    var itemLength = items.length;
                    arrItems.push(itemObjects);
                }
                dfd.resolve(arrItems, itemLength);
            },
            function(){ // Return to button click function
                dfd.reject(args.get_message());
            }
        ); // End ClientContext
    }); // End dfd
  return dfd.promise();
} // End getSelected

The reason for this is that creating a variable without a value makes it undefined, resulting in 'UndefinedUnicorn' when trying to concatenate with 'Unicorn'. If you want to declare a variable for this purpose, use "var x = ''".

If, for example, you aim to sum the length of all "items", the function should be modified as follows:

        function(){ // Return to button click function
            var itemLength = 0;
            for (var j = 0; j < items.length; j++) {
                var itemObjects = items[j].get_item("Title");
                itemLength += itemObjects;
                arrItems.push(itemObjects);
            }
            dfd.resolve(arrItems, itemLength);
        }

However, it's not entirely clear what you are trying to achieve here.

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

Javascript code experiences a shift in two different styles within a single conditional statement

I'm new to web design and I'm having trouble getting this code to work properly. Can anyone help me fix it so that both styles are applied correctly? // Access the sign_up modal window var modal = document.getElementById('id01'); // A ...

Differences in React projects utilizing materialize-css compared to those using react-toolbox or material-ui

Is there a difference in technical benefits or code reliability when directly using material-css in JSX versus utilizing JSX specific libraries like material-ui or react-toolbox? Conversely, could using JSX libraries like material-ui or react-toolbox provi ...

Encountering an issue when trying to download a PDF from an Angular 6 frontend using a Spring Boot API - receiving an error related to

When I directly call the Spring Boot API in the browser, it successfully creates and downloads a PDF report. However, when I try to make the same GET request from Angular 6, I encounter the following error: Here is the code snippet for the Spring Boot (Ja ...

Utilizing "this" correctly within JavaScript objects

Can someone help me understand how to access enums.ROCK within the prop in the code snippet below? I keep getting an error that says Uncaught TypeError: Cannot read property 'enums' of undefined. Please pay attention to the comment ERROR LINE. c ...

Utilize data retrieved from an API to customize the appearance of buttons through the combination of React and Sass styling techniques

I retrieved data from an API and used it to create a list of buttons. The data I received includes names and color codes. { name: "bob", colorCode: "#DC7472" }, { name: "ben", colorCode: "#69DCD1" }, { name: &q ...

Is there a way to sequentially execute requests in a loop?

My goal is to extract a list of URLs from the request body, pass them to a request function (using the request module) to retrieve data from each URL, and then save that data to MongoDB. The response should be sent only after all requests are completed, in ...

I am experiencing an issue where the result is not appearing on the input tag within my

<script> <form action="do-add-cek.php" id="myForm" method="post" enctype="multipart/form-data"> <div class="form-group"> <label> ...

Exploring AngularJS capabilities in showing server validation messages along with creating dynamic forms

On the server side, I am utilizing Express along with sequelizejs. Let's say we have this particular view: (It is included as <div ng-include src="'views/users/_form.html'"></div> in the new, edit view.) <div class="form-gro ...

Combining strings in the C programming language often results in unexpected characters

After creating a program to concatenate two strings, I noticed that when the character array is too small, some additional characters end up in the final output string. Here is the faulty code: char c[3] = "abc"; char d[3] = "def"; cha ...

What could be causing my second ajax call to render the page unresponsive?

I am encountering an issue with my AJAX call. It works fine on the first attempt, but when I try to call it a second time, the page becomes unresponsive. I am not sure what is causing this issue. The code is located within the document ready function. The ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...

Collection of items consists of identical objects repeated multiple times

Multiple objects are being created and then pushed into the array objArr: var objArr = []; var obj = {}; var height = [9,8,7,3,6,5,2,4]; for (var i = 0; i < 8; i++) { debugger; var mountainH = height[i]; obj.h = mountainH; obj.index = i; o ...

Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this: <script> myArray=<?php echo $array;?>; app={ myArray:myArray, myIndex:myArray.length-1, back:function(){this.myIndex--;console.log("You clicked back");}, forward:function(){this.myIndex++} } ...

Inform the PHP backend that the browser has been closed by the frontend Angular application

Currently, I am working on an Angular project that is interacting with a backend project created using PHP and ZF3. I am trying to figure out the most efficient method of informing the backend project when the user closes the browser window. Initially, I ...

Insert the video link and preview it with live option

Currently working on a form that allows users to input a video URL. The form will be a standard input field where they can enter a URL such as: http://video.google.com/videoplay?docid=1299927595688205543 I want to include a button within the form labeled ...

Converting a text area into a file and saving it as a draft in the cloud with the

Can content from a text area be converted into a file of any chosen format and saved in the cloud? Additionally, should every modification made in the text area automatically update the corresponding file stored in the cloud? ...

Tips for efficiently transferring a retrieved object from App.js to a child component in ReactJS version 16 and above using asynchronous methods

TL;DR How can I pass a fetched object from App.js to a child component asynchronously? Do I need to wait for the data to be completely fetched before returning App.js? If so, how can I achieve this? In an attempt to create a dashboard using react-chartj ...

What is the process for converting a string into a date while disregarding the time zone

Due to the way dates are stored, it is important for me to retrieve them exactly as they are stored, but time zones are causing issues. moment("2020-10-28T08:41:00.000Z").format("YYYY-MM-DD HH:mm") // Result: 2020-10-28 09:41 However, ...

Programmatically link an Angular JS model to a template using binding

When given an HTML template like the following: <div class="info"> <div class="title"><a href="property-detail.html">{{title}}</a></div> <div class="location">{{location}}</div> <div class="property ...

Experiencing difficulty in parsing the JSON document

I am struggling with reading a .JSON file (todo.json) in my Angular.Js project. The file is stored on the server, and all static files are saved within the 'public' folder of my basic Express server. Even though I can access the todo.json file di ...