Script syncing two records of different types

Hi guys,

I’m not a developer, or programmer by any means, and I’m struggling to have two different types of fields syncing. It seems my only problem is that Field2 (the target) is a Linked Record field, and Field1 is a Single Line text field. I have no clue what to do at this point…

The script i have so far looks like this

// get the table
let table = base.getTable("Table1");
let query = await table.selectRecordsAsync({fields: table.fields});


// loop through the records
for (let record of query.records) {

        // now update Field 2 with the array of IDs in Field 1
        let msCopy = await table.updateRecordAsync(record, {
            "Field2": record.getCellValue("Field1")
        })    
    }

Linked Record fields need to be supplied a value which is an array of objects where each object contains the ID of the record to be linked, like this:

"Field2": [{id: "recXXXXX..."}]

You will need to do some sort of filter of whatever Table is being linked to in order to find the one record whose primary field matches the cell value of “Field1”.

Or, you could try using an Automation to do this instead. The “Update Record” action step for automations can feed in the “names” of records or the IDs, so you could simply insert the value of Field1 that way.

As a matter of advice, since your script appears to be looping through what could be several records and making those updates one by one, the script could be rewritten to be a bit more efficient by performing the updates in batches.

// get the tables
let table1 = base.getTable("Table1");
let query1 = await table.selectRecordsAsync({fields: table1.fields});
let records1 = query1.records

let table2 = base.getTable("Table 2")
let query2 = await table.selectRecordsAsync({fields: ["Name of Primary Field"]})
let records2 = query2.records

let updates = []

// loop through the records
for (let record of records1) {
    let match = records2.find(r => r.getCellValueAsString("Primary Field") === record.getCellValueAsString("Field1"))
    if(match) {
        updates.push({id: record.id, fields: {"Field2": [{id: match.id}]}})
    }
}

// update the records
while (updates.length > 0) {
    await table1.updateRecordsAsync(updates.slice(0, 50));
    updates = updates.slice(50);
}
1 Like