Add elements to the array, extract elements from the array

tag, I am currently facing a challenge with transferring multiple attributes from SharePoint list items into an array (only selected items in a view) and then passing that array to a function where I can extract and use these attributes to create new list items in a different list. Essentially, my goal is to copy specific fields from one set of list items to another. The main obstacle I am encountering is figuring out how to properly pack the attributes obtained using the getSelected function and then unpack them within the writeSelected function. Despite investing significant time researching online resources and forums for guidance on this process, I have struggled to find a solution. In the best-case scenario, the results I have achieved thus far return as undefined...
// Retrieving selected items from a view
function getSelected() {
    listName2 = "Customer Locations";
    var Astate, Aname;
    var ctx = SP.ClientContext.get_current();
    var clientContext = new SP.ClientContext(); 
    var targetList = clientContext.get_web().get_lists().getByTitle(listName2);
    var SelectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
    var items = [];
    for (var i in SelectedItems) {
        var id = SelectedItems[i].id;
        var item = targetList.getItemById(id);
        clientContext.load(item, "A_x0020_State", "A_x0020_Name");
        items.push(item);
    } // End for
    clientContext.executeQueryAsync(function() {
        var results = [];
        for (var i = 0; i < items.length; i++) {
            items.Aname = item.get_item('A_x0020_Name');
            items.Astate = item.get_item('A_x0020_State');
            results.push( {A_name: results[items.Aname], A_state: results[items.Astate]} );
            console.log(results.A_name);
        } //End for
    }, failure); //End ClientContext
} //End getSelected

//Adding selected items to the Sites list in WCAP
function writeSelected(results) {
    listName4 = "Sites";
    for (var k in results) {
        var clientContext = SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle(listName4);
        var item = new SP.ListItemCreationInformation();
        var oListItem = oList.addItem(item);
        oListItem.set_item("Link_x0020_ID", fieldValue);
        oListItem.set_item("A_x0020_Name", ???);
        oListItem.set_item("A_x0020_State", ???);
        oListItem.update();
        clientContext.load(oListItem);
        clientContext.executeQueryAsync(success, failure)
    } //End for
} //End writeSelected

Answer №1

For those looking to transfer list items from one list to another, you can utilize the code snippet provided below:

<button type="button" id="copyButton" onclick="copyListItems()">Copy Items</button>  

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var sourceListName = "Source List Name";
var destinationListName = "Destination List Name";

function copyListItems() {
    // execute function to duplicate all items from source list to destination list
    getSourceListData().then(copyItemsToDestination);
}

function getSourceListData() {
    var deferred = $.Deferred();
    var context = SP.ClientContext.get_current();

    this.sourceListObj = context.get_web().get_lists().getByTitle(sourceListName);
    this.sourceFields = sourceListObj.get_fields();
    this.destinationListObj = context.get_web().get_lists().getByTitle(destinationListName);

    context.load(sourceListObj);
    context.load(sourceFields);
    context.load(destinationListObj);

    var elements = sourceListObj.getItems(SP.CamlQuery.createAllItemsQuery());
    context.load(elements);

    context.executeQueryAsync(
        function () { deferred.resolve(elements); },
        function (sender, args) { deferred.reject(sender, args); }
    );
    return deferred.promise();
}

function logMistake(sender, args) {
    console.log('An error has occurred: ' + args.get_message());
}

function logAchievement(sender, args) {
    console.log('List items successfully copied.');
}

function copyItemsToDestination(items) {
    $.when.apply(items.get_data().forEach(function (srcItem) { transferItem(srcItem); }))
     .then(logAchievement, logMistake);
}

function transferItem(srcItem) {
    var deferred = $.Deferred();
    var context = srcItem.get_context();

    var newListItemInfo = new SP.ListItemCreationInformation();
    var targetListItem = destinationListObj.addItem(newListItemInfo);

    var fieldEnum = sourceFields.getEnumerator();
    while (fieldEnum.moveNext()) {
        var field = fieldEnum.get_current();
        
        if (!field.get_readOnlyField() && 
            field.get_internalName() !== "Attachments" && 
            !field.get_hidden() && 
            field.get_internalName() !== "ContentType") 
        {
            var srcFieldValue = srcItem.get_item(field.get_internalName());
            if (srcFieldValue != null) {
                targetListItem.set_item(field.get_internalName(), srcFieldValue);
            }
        }
    }

    targetListItem.update();
    context.load(targetListItem);

    context.executeQueryAsync(
        function () { deferred.resolve(); },
        function (sender, args) { deferred.reject(sender, args);
    });
    return deferred.promise();
}
</script>

Related Links:

Guide on Copying SharePoint List Items Between Lists

Using REST/JSON to Duplicate List Items

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

The error message for ExpressJS states: "Headers cannot be set after they have already been sent."

Currently, I'm facing a challenge with ExpressJS and am having trouble finding the necessary documentation to resolve it. Technology Stack: body-parser: 1.17.0 express 4.15.0 multer: 1.3.0 MongoDB Postman The current view consists of 3 fields: n ...

What is the reason for requiring this to be passed as an Array instead of a String?

I'm currently learning node.js through a tutorial in a book titled Node Web Developments. Issue: I am struggling with understanding why an array [] is being passed as the 3rd argument from mult-node.js to the required function htutil.page(), instead ...

How can you alter a property within an array of records retrieved from a Mongoose query?

const images = await tbl .find({ creator_id: req.user._id, }) .select({ creator_id: 0, }) .exec() .then((images) => images.forEach((image) => { image.file_name = process.env.IMAGE_ ...

Can you provide tips on using Ajax to store a cache file?

I've created a javascript/ajax function that retrieves a json file from an external server. The functionality I'm trying to implement includes: Fetching the json file from the external server Saving the json file on the local server Checking if ...

Guide to uploading a recorded audio file (Blob) to a server using ReactJS

I'm having trouble using the react-media-recorder library to send recorded voice as a file to my backend. The backend only supports mp3 and ogg formats. Can anyone provide guidance on how to accomplish this task? Your help would be greatly appreciated ...

Traversing an array of objects using D3.js

I'm attempting to create a row of bars that are all the same height and width based on their titles. I have an array of 100 objects, each with a key called results containing another array of 20 objects. This means I should end up with a row of 2000 b ...

Issue with Many to Many Relation Query in Objection JS, Postgres, and Express Resulting in 'TypeError: Cannot Read Property 'isPartial' of Null' Error

I have a challenge connecting the 'products' table to the 'tags' table using a many-to-many relationship structure with the 'products_tags' table. Upon executing const product = await Product.relatedQuery('tags').fi ...

Encountering a problem with the state error while trying to modify an input field during onChange event

Whenever I pass state down from a parent component, the setState function keeps triggering an error that says setEmail is not a valid function on change event. Is there a simple solution to fix this issue? Every time I type a string into the email input f ...

Assess html code for Strings that include <% %> tags along with embedded scripts

Having a small issue with my code where I am receiving an HTML response from a web service as a java String. I need to display this String as HTML on my webpage, but the problem is that there are some script tags in the form of <% ... %> which are sh ...

Some variables are not being properly tracked by Google Analytics

Within the document.ready() function of the primary GSP layout in my application, I have included the following code: var pageTitle = document.getElementsByTagName('title')[0].innerHTML; if('index' == 'list') { pageTitle ...

How can you verify the anticipated log output in the midst of a function execution with Jest unit testing?

Below is a demonstration function I have: export async function myHandler( param1: string, param2: string, req: Request, next: NextFunction, ) { const log = req.log.prefix(`[my=prefix]`); let res; If (param1 === 'param1&a ...

My method for updating form input properties involves switching the disable attribute from "false" to "true" and vice versa

I have a form that uses Ajax to submit data. Once the user submits the form, the text is updated to indicate that the data was sent successfully, and then the form is displayed with the fields filled out. I want to display the form but prevent users from r ...

Is there a way to include multiple web parts that utilize an angularjs module?

How do I incorporate multiple web parts in SharePoint using AngularJS modules? I have a web part where I've utilized AngularJS. The issue arises when attempting to add this web part multiple times on a page - separating the Angular module names poses ...

extracting key-value pairs from nested arrays in javascript objects

As a beginner in javascript, I am facing an issue that may seem basic to others. Here is the json data I am working with: { "statusCode": 200, "status": "success", "data": [ [ { "city": "Alexandria", ...

Tips for successfully transferring a JSON object from jQuery to a JavaScript function

Can you help me with accessing data in a JavaScript function after populating it dynamically on an HTML page through an Ajax call? Issue: I am trying to invoke a JavaScript function when clicking on a button after populating the data. However, I am facing ...

How to retrieve controller property from a different Class in AngularJS

While working with AngularJS today, I came across an issue that I need help resolving. Here is the code snippet in question: app.controller("SomeController", function(){ this.foo = true this.changeFoo = function(bool){ ...

Adjust the horizontal position of the background by +/- X pixels

Is there a way to adjust the background-position by a specific distance, say 20px, from its original position? For example: $(".selector").animate("slow").css("backgroundPosition", "center -=20px"); (Unfortunately, this approach doesn't yield the d ...

Is there an issue with the real-time update of graphics pixels in Java?

At this moment, my main goal was to display my game window on the screen. However, I encountered an issue where the color red is not displayed across the entire window. I have reviewed my code multiple times but can't seem to identify the problem. Her ...

What is the best way to access the current value and name of a textbox in real-time using

How can I retrieve the value of a textbox in JavaScript using onblur and on keyup events, while also performing real-time checking for each individual textbox using "this keyword"? Here is my JSFiddle link. Can you assist me in modifying it? ...

Encountering a Mongoose issue while attempting to load model files from a separate Mean.js project using the require function

I am currently working on a Mean.js project and in the process of familiarizing myself with this environment. To conduct some experiments, I created a parallel project for testing purposes in a separate folder where I am not using the Mean.js framework but ...