|
await(async() => { |
|
const contextInfoURL = location.href.replace(/(^\w+:\/\/[^/]+(?:\/sites\/[^/]+)?).*/i, '$1/_api/contextinfo'); |
|
const digest = (await (await fetch(contextInfoURL, { |
|
method: 'POST', |
|
headers: { |
|
Accept: 'application/json' |
|
} |
|
})).json()).FormDigestValue; |
|
|
|
const sourceListName = 'TrainingVideoLinks'; // Replace with your source list name |
|
const newListName = `TrainingVideoLinksOLD`; // New list name with timestamp |
|
|
|
const fieldNames = (await(await fetch(`${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/GetByTitle('${sourceListName}')/Fields`, { |
|
method: 'GET', |
|
headers: { |
|
Accept: 'application/json;odata=verbose' |
|
} |
|
})).json()).d.results.filter(f => !f.ReadOnlyField).map(f => f.InternalName); |
|
|
|
// Copy items from the source list to the new list |
|
const itemsResponse = await fetch(`${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/GetByTitle('${sourceListName}')/Items`, { |
|
method: 'GET', |
|
headers: { |
|
Accept: 'application/json;odata=verbose' |
|
} |
|
}); |
|
if (!itemsResponse.ok) { |
|
console.error('Failed to fetch items from source list.'); |
|
return; |
|
} |
|
const items = (await itemsResponse.json()).d.results; |
|
|
|
for (const item of items) { |
|
const newItem = { |
|
__metadata: { type: 'SP.ListItem' } |
|
}; |
|
for (const [key, value] of Object.entries(item)) { |
|
// If the value is null or if it is not a field we care about or if it is |
|
// a field that should be deferred then skip it. |
|
if (!fieldNames.includes(key) || value?.__deferred) continue; |
|
// Get the value without any private properties (eg. __metadata, __deferred). |
|
const newValue = JSON.parse(JSON.stringify(value, (key, value) => { |
|
if (key !== '__deferred') return value; |
|
})) |
|
// If the value without __metadata is an empty object then skip it. |
|
if (newValue != null && typeof newValue === 'object' && !Object.keys(newValue).length) continue; |
|
newItem[key] = newValue; |
|
} |
|
console.log({item, newItem}); |
|
const newItemUrl = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/GetByTitle('${newListName}')/Items`; |
|
const newItemResponse = await fetch(newItemUrl, { |
|
method: 'POST', |
|
headers: { |
|
Accept: "application/json;odata=verbose", |
|
"Content-Type": "application/json;odata=verbose", |
|
"X-RequestDigest": digest |
|
}, |
|
body: JSON.stringify(newItem) |
|
}); |
|
if (!newItemResponse.ok) { |
|
console.error(`Failed to copy item with ID ${item.ID}.`); |
|
} else { |
|
console.log(`Item with ID ${item.ID} copied successfully.`); |
|
} |
|
} |
|
|
|
console.log(`List '${newListName}' has been created with structure and data copied.`); |
|
})(); |