How to update doc fields using office.js api

Baljeet Kaur 0 Reputation points
2023-03-15T10:14:14.43+00:00

I want to update all custom property fields of document with new value if they are present. Here is my code

 Word.run(function (context) {
	var customDocProps = context.document.properties.customProperties;
	// first, load custom properties object
	context.load(customDocProps);
	return context.sync()
		.then(function () {
			// now load actual property
			var filenameProp = customDocProps.getItemOrNullObject("PW", { matchPrefix: true });
			context.load(filenameProp);
			return context.sync()
				.then(function () {
					if (customDocProps.items.length > 0) {
						var fields = context.document.body.fields.load("items");
						fields.load(["code", "result"]);
						return context.sync()
							.then(function () {
								if (fields.items.length > 0) {
									$.each(fields.items, function (i, k) {
										$.each(customDocProps.items, function (j, l) {
											if (k.code.trim().replace(/\s\s+/g, ' ').split(' ')[1].toLowerCase() == l.key.toLowerCase()) {
												//replace if values are different
												if (k.result.text != l.value) {												   
													k.result.insertText(k.result.text, l.value);
													k.load(["code", "result"]);
													return context.sync();
												}
												else {
													return false;
												}
											}
										});
									});
								}
							});
					}
				});
		});
}).catch(function (error) {
	debugger;
	console.log('Error: ' + JSON.stringify(error));
	if (error instanceof OfficeExtension.Error) {
		console.log('Debug info: ' + JSON.stringify(error.debugInfo));
	}
});
Microsoft 365 and Office | Development | Office JavaScript API
{count} votes

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.