Does anyone have a "struct merge" util function ha...
# cfml-general
s
Does anyone have a "struct merge" util function have lying around? I'm looking for a function that merges two structs (recursively).
Example input:
Should yield 1 merged struct
b
Can you provide the expected result struct too please?
s
@brettpr
but if the second struct had an item at
foo[1].bar[1]
that should be placed at the
[undefined array element]
location.
Even chatgpt isn't able to solve this one for me.
m
haven't used it, but might try https://cflib.org/udf/structBlend
b
It's just two lines of code. You will see how simple it is if you assign each entity to a variable.
// Given
struct1.lorem.ipsum={};
arr1=["",struct1];
struct2={"bar":arr1};
struct3={"foo":[struct2]};
//writedump(struct3);
struct4.bar.foo={};
arr2=[struct4];
struct5={"lorem":arr2};
struct6={"foo":[struct5]};
//writedump(struct6);
// Your result implies you wish
// to append struct2 and struct5
structAppend(struct2,struct5,true)
// The combined (or, as you say, "merged") result
combinedStruct={"foo":[struct2]};
writedump(combinedStruct);
a
Example input:
Instead of passing us a picture of it being dumped, can you post the code that created it. This helps us reproduce the situation without having to type it ourselves. This applies to any situation, not just this one. A picture of code / its output / error messages is seldom the best primary way of sharing such information. Text. Start with text that can be copy and pasted and reused.
s
Good point @Adam Cameron, I'll try to remember it in case of a next question. I apologize for the inconvience.
a
I would probably have given the team something like this: https://trycf.com/gist/b27b639772071b3868c6a78ad14b5f45/lucee5?theme=monokai
👍 1
What is the rule if both
s1
and
s2
have the same key, and they're not both structs (so accordingly can be handled recursively). Throw a
CannotBeMergedException
?
s
Yes, that would be an acceptable action for that case.
a
Here's a starting point: https://trycf.com/gist/e1fbafcabf6c08b20edde2b5341bd078/lucee5?theme=monokai Largely untested other than that one case, but you get the general idea.
❤️ 1
Had you provided actual code, I'd've tested with your own values.
✔️ 1