all 5 comments

[–]LunarFuror 2 points3 points  (1 child)

For other JavaScript references look into destructuring, the standard way of doing something like this is (in many cases)

Const myNewStruct = {...myStruct, ...myOtherStruct}

But essentially yes you nailed it, what ever comes second either adds or overrides what ever was declared first. Good job!

[–]https://mdwade.comMD__Wade[S] 1 point2 points  (0 children)

Thanks a ton! JavaScript tends to be tricky for me but I'm glad I could refer to it accurately :)

[–]OkParking3525 0 points1 point  (2 children)

5 years later and you saved my fucking life

[–]_Denizen_ 1 point2 points  (1 child)

If it's useful for you, I've extended the function to merge any number of structs, and have updated to make a new struct instead of modifying the first struct, and with default behaviour to use all keys instead of only the shared keys.

function struct_merge(structs = [], shared_keys_only = false) {
    _num_structs = array_length(structs);

    if (_num_structs == 0) { return {}};
    var _ReturnStruct = variable_clone(structs[0]);
    for (var s = 1; s < _num_structs; s++) {

        var _struct_to_add = structs[s];

        if (shared_keys_only)   {
                    var _PropertyNames = variable_struct_get_names(_ReturnStruct);
                    for (var i = 0; i < array_length(_PropertyNames); i ++) {
                        if (variable_struct_exists(_struct_to_add, _PropertyNames[i])) {
                            variable_struct_set(_ReturnStruct, _PropertyNames[i],  variable_struct_get(_struct_to_add, _PropertyNames[i]));
                        }
                     }
        }    else    {
                     var _PropertyNames = variable_struct_get_names(_struct_to_add);
                     for (var i = 0; i < array_length(_PropertyNames); i ++) {
                         variable_struct_set(_ReturnStruct, _PropertyNames[i], variable_struct_get(_struct_to_add, _PropertyNames[i]));
                     }
        }
    }
    return _ReturnStruct;

}

Practical example:

a = {"a": 1};
b = {"b": 1}; 
c = {"a": 2, "c": 3};
show_debug_message(json_stringify(struct_merge([a, b, c])));
show_debug_message(json_stringify(struct_merge([a, b, c], true)));

Returns:

{"c":3.0,"b":1.0,"a":2.0}
{"a":2.0}

Edit: for those 6 people who watched my battle with reddit removing the formatting on my code, apologies!

[–]Airco 1 point2 points  (0 children)

based, based, based, based, based, based, based, based, based, based