Skip to content

set — GTM Variable Template for Object

VARIABLES › OBJECT
set EXTENDED Object

Sets a property on an object at a given path, creating nested structures as needed.



Examples

Set simple property
INPUT
Target Object: {name: 'John'}
Property Path: age
Value to Set: 30
OUTPUT
John
Set nested with auto-create
INPUT
Target Object: {user: {}}
Property Path: user.profile.name
Value to Set: Jane
OUTPUT
Jane

GTM Configuration

This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.

set
Target Object
💾 The object to modify. Warning: This function mutates (modifies) the original object.

Supported formats:
  ✓ Object variable: {{myObject}}
  ✓ Object literal
Property Path
💾 The path where to set the value. Creates nested objects automatically if they don't exist.

Supported formats:
  ✓ String (dot notation): "user.profile.name"
  ✓ Array: ["user", "profile", "name"]
Value to Set
💾 The value to set at the specified path.

Supported formats:
  ✓ Any type: string, number, boolean, object, array
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the target object before setting the value (e.g., clone object to avoid mutation, normalize structure).
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the modified object before returning it (e.g., obj => JSON.stringify(obj), obj => Object.freeze(obj)). Useful for chaining transformations on the output.
Target Object object
💡 Type any text to see the result update live
🎯 Using special value — click input to type instead
Test with:
Falsy
Truthy
Property Path array
Value to Set number
set()


Under the Hood

📜 View Implementation Code
/**
 * Sets a value at a given path in an object, creating nested objects as needed.
 *
 * @param {Object} data.src - The target object to modify.
 * @param {string|Array} data.pth - The path where to set the value (e.g., "a.b.c" or ["a", "b", "c"]).
 * @param {*} data.val - The value to set at the path.
 * @param {Function|string} [data.out] - Optional output handler: function to transform result or string with format.
 *
 * Direct-mode specific parameters:
 * @param {Function} [data.pre] - Optional pre-processor function to transform src before processing.
 * 
 * @returns {Object} The modified object (mutates the original object).
 *
 * @framework ggLowCodeGTMKit
 */
const getType = require('getType');

const set = function(object, path, value) {
    if (getType(object) !== 'object' || object === null) {
        return object;
    }
    
    const pathParts = getType(path) === 'array' 
        ? path.map(part => part.toString()) 
        : path.split('.');
    
    let current = object;
    for (let i = 0; i < pathParts.length; i++) {
        const key = pathParts[i];
        if (i === pathParts.length - 1) {
            current[key] = value;
        } else {
            if (getType(current[key]) !== 'object' || current[key] === null) {
                current[key] = {};
            }
            current = current[key];
        }
    }
    
    return object;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// set - Direct mode
// ===============================================================================

const applyCast = (castFn, value) => safeFunction(castFn)(value);
const value = applyCast(data.pre, data.src);
return out(set(value, data.pth, data.val));
// ===============================================================================
// set(...) – Apply Mode
// ===============================================================================
/*
return function(object, path, value) {
   path = data.rp1 ? data.pth : path;
   value = data.rp2 ? data.val : value;
   return out(set(object, path, value));
};
*/
🧪 View Test Scenarios (5 tests)
✅ '[example] Set simple property'
✅ '[example] Set nested with auto-create'
✅ Test with array path format
✅ Test overriding existing nested property
✅ Test setting deeply nested property in empty object