同じレコード内の複数のサブテーブルを日付基準で並べ替える

@Kenichi35

下記のような形でいかがでしょうか?

// テーブル名に対しての日付フィールドの紐づけ配列
const tableFieldMappings = [
	{ tableFieldName: "テーブル1", dateFieldName: "日付1" },
	{ tableFieldName: "テーブル2", dateFieldName: "日付2" },
	{ tableFieldName: "テーブル3", dateFieldName: "日付3" },
	{ tableFieldName: "テーブル4", dateFieldName: "日付4" },
]

// ボタンへ付与する並べ替え機能
const sortTable = async () => {
	if (!window.confirm("テーブルを並べ替えますか?")) return
	try {
		const res = await kintone.app.record.get()
		let record = res.record
		// 並べ替え部分のデータを格納する変数
		let newRecordData = {}

		// 配列分回して並べ替え後のデータ収集
		tableFieldMappings.map(item => {
			const sortItem = sortTableByDate(record, item.tableFieldName, item.dateFieldName)
			newRecordData = { ...newRecordData, ...sortItem }
		})

		await updateRecord(record["レコード番号"].value, newRecordData)
	} catch (err) {
		console.log(err, "並び替えのエラー")
	}

}

// 並べ替え
const sortTableByDate = (record, tableFieldName, dateFieldName) => {
	let tableValue = record[tableFieldName].value
	// 日付基準で並び替え
	tableValue.sort((a, b) => {
		const dateA = new Date(a.value[dateFieldName].value);
		const dateB = new Date(b.value[dateFieldName].value);
		return dateB - dateA;
	})
	return { [tableFieldName]: { value: tableValue } }
}

// 更新処理と画面の更新
const updateRecord = async (recordId, newRecordData) => {
	// 更新データ
	const body = {
		app: kintone.app.getId(),
		id: recordId,
		record: newRecordData
	};

	console.log(newRecordData)

	// データの更新
	await kintone.api(kintone.api.url('/k/v1/record.json', true), 'PUT', body);
	// 画面の更新
	window.location.reload()
}

// kintoneへボタン追加
const addSortButton = () => {
	// 詳細画面
	kintone.events.on("app.record.detail.show", (event) => {
		// メニュースペースにボタンの設置
		const el = kintone.app.record.getHeaderMenuSpaceElement()
		const button = document.createElement("button")
		button.innerText = "並べ替え"
		// ボタンにソート機能を設定
		button.addEventListener("click", sortTable)
		el?.appendChild(button)
		return event;
	});

}

addSortButton()
「いいね!」 1