Is it possible to add a new entry to a SharePoint list using REST API without statically specifying the field names?

I am currently in the process of creating a new list item in a SharePoint list using the REST API. To make the process more flexible, I am storing the field names in an array that will be dynamically updated by another function. However, I have encountered a roadblock while trying to reuse my existing code. The code is failing at the metadata section where I attempt to iterate through the array and add each element as a field name. Each element in the array corresponds to a field name.

var favorite=[];
   //favorite is an array of field titles dynamically updated with another function
   //I aim to dynamically populate this array while creating a new list item

var item = {"__metadata": {"type": "SP.Data.TestCatalogListItem"},for(int i=0; i<favourite.length;i++){favorite[i]:cells[i]}};

_createListItem(item);

function _createListItem( listItems,listname, success, failure) {
$.ajax({
url: "https://site/_api/web/Lists/getbytitle('MYLIST')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(listItems),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
//success(data);
},
error: function (data) {
//failure(data);
}
});
}

Answer №1

If you haven't already, consider moving the for loop into the _createListItem function for better organization.

Although I personally have not used the ajax method, I typically utilize the JSOM and built-in SP functions. In my approach, I pass in an object containing up to 7 keys: listName, folderName, fields, successFunctionCallback, successFunctionParams, failedFunctionCallback, and failedFunctionParams. The fields value consists of an array of field names and values similar to what you have. Within the create function, I iterate over the fields and assign the corresponding values. In your case, you would just need to do the same but construct a data variable.

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

Can a package-lock.json file be created without running an npm install command?

Is there a way to create only a package-lock.json file without having to redo the npm install process? I'm looking to generate the lock file without reinstalling any of the package files. Is this achievable? ...

Using Node.js Puppeteer to interact with dynamically generated elements

Currently, I'm utilizing puppeteer for node.js version 13.3.1 to develop a bot that will automate job applications on LinkedIn. The code I have so far is as follows: const puppeteer = require('puppeteer'); const SEARCHPARAM = "react& ...

Dropdown with multiple selections organized in a hierarchical structure

I am in need of the following : Implement a drop-down menu that reflects hierarchical parent-child relationships. Include a checkbox for each node to allow for selection. If all child nodes are selected, their parent node should be automatically ch ...

Issue with improper lighting on Three.Geometry objects when using LambertMaterial in Three.js

After enhancing my initial version of this inquiry (previously asked question) with a JSFiddle showcasing the latest build of Three.JS and illustrating the lighting issue on Three.Geometry, I encountered difficulties with dependencies in Stack Snippets. Ho ...

Placing an element on the page starting from the bottom and moving it towards the

Is there a way to display items on a page from bottom to top, similar to how messages are shown in a chat? Here's an example: .chart div { font: 10px sans-serif; background-color: steelblue; padding: 3px; margin: 1px; color: white; disp ...

How to retrieve an object once it exits the viewport in JavaScript

I am seeking guidance on how to reset an object to its initial position (0) once it exits the browser window. Currently, I have an image that moves when you click on the up/down/left/right buttons, but it eventually extends beyond the browser window. Belo ...

Issue with nodes/JavaScript: Array objects not being properly updated

Being new to Javascript and Node.js, I attempted to code a simple program that generates an array of planes with varying index values. I started by defining a plane object with default values and tried to update the index value in a for loop. However, whe ...

Using threejs to pass multiple secondary geometries into vertex shaders

Suppose I have a geometry that I am using to create points or an InstancedMesh by utilizing the vertices. However, if I want to change this underlying geometry to something else - such as from a cone to a sphere - that has the same number of vertices, how ...

Posting a JavaScript string to a C# backend in ASP.NET Core MVC: A step-by-step guide

I am a beginner in ASP and facing an issue while attempting to pass a string from my JavaScript code to my controller. The intention is to utilize this string for querying my database. JavaScript function findEmployees(userCounty) { $.ajax({ t ...

Utilizing Node.js to Retrieve Data from MySQL

Hi there, I'm new to NodeJS and I'm curious about how to fetch a MySQL query like we do in PHP. $query = mysql_query("SELECT * FROM accounts"); while($fetch = mysql_fetch_array($query)) { echo $fetch['Username']; } How would this be ...

What methods does Flipkart employ to access DOM elements for integration testing purposes?

Something that caught my eye recently is that Flipkart uses mostly random class names in their DOM elements, reminiscent of the styled-components library. I'm curious to know how they go about accessing these DOM elements for integration testing. UP ...

Troubleshooting CSS override issues when swapping components in ReactJS

Access.js import React from 'react' export default class Access extends React.Component { componentWillMount(){ import ('./styles/access_page.css'); } .... <Link to="/new-account">Sign Up</Link> } Cr ...

Challenge with NodeJS, Angular Seed, Gulp, Jasmine, and Karma

Starting an Angular Seed project and everything was working fine. I managed to launch the Jasmine browser, but encountered issues with my specs not working. In an attempt to fix this, I added a karma.conf file, which unfortunately broke the Jasmine browser ...

Is there a way to undo the changes made by the following execution using Javascript?

Similar Question: How can I delete a cookie using JavaScript? javascript:void(document.cookie=”PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;path=/; domain=.google.com”); To undo the action perfor ...

Is it advisable to send an object as an argument in a function?

Here's the code snippet I'm working with: const failure1 = false; const failure2 = false; function callbackFunction(callback, errorCallback) { if (failure1) { errorCallback({ name: 'Negative event1 occurred', ...

Exploring web pages with JavaScript events

I am currently trying to compile a list of singles that were released in the year 2018 from allmusic.com. While accessing their advanced search page and setting the parameters is simple enough, the challenge lies in extracting the information manually. Th ...

Zero-length in Nightmare.js screenshot buffer: an eerie sight

I'm currently working on a nightmare.js script that aims to capture screenshots of multiple elements on a given web page. The initial element is successfully captured, but any subsequent elements below the visible viewport are being captured with a l ...

Navigate to a pathway, trigger an error notification, and transfer to a different destination

Currently, my project involves working with nodejs, expressjs, and javascript... I have implemented a "middleware" function designed to prevent access to certain routes by users who are not logged in. However, I am facing an issue where I cannot send an a ...

Navigating through object arrays using a loop

I have multiple arrays within an object that I would like to iterate through using numeric values. This is necessary in order to assign them to different slots in an accordion loop. The JSON file containing the data looks similar to this (Pokemon used as a ...

Creating multi-dimensional arrays using array lists with Axios and Vue.js

My knowledge of axios and JavaScript is limited, and I find myself struggling with creating a multi-dimensional array. 1. This is how I want my data to be structured : https://i.stack.imgur.com/kboNU.png userList: [ { ...