Prevent coffeescript method from adding a new element to a variable that called it

66 Views Asked by At

I'm looping through and object and want to contain matching results in a new object. Non-matching results I want to discard/ignore.

The problem is that I get an object with empty entries where there was no match from within the method e.g.

[[[[[null, null], null, null], <Layer id:10 name:card2 (0,1033) 894x812>]]]

All I really want is just

<Layer id:10 name:card2 (0,1033) 894x812>

This function is supposed to recursively look inside an object until if finds the first match instance and returns it. (I would also settle for collecting all matching instances, rather than just the first)

r = (n, obj) ->
    if obj.name is n
        obj
    else if typeof obj is "object"
        obj = obj.subLayers
        for key, value of obj
            if value.name is n 
                value
            else if value.subLayers.length
                r(n, value)
            else
                null

l = r("card2",wrapper)
print l

For context, this is for Framer.js and the above example is here http://share.framerjs.com/6qax51amay0v/

I'm not sure if that matters for this example where what I'd like to do is skip the non-matching values altogether but r() always returns something and creates an empty entry within the variable that's capturing the output. It maybe that returning nothing is the answer or that it shouldn't add another object element []

1

There are 1 best solutions below

0
On

I did a quick test

a = null
typeof(a) -> returns "object"

That could be the issue?