d3 adding data attribute conditionally

You don’t need to call each() or filter()… The attr() function will do this for you internally. Just call it with a function instead of a value, and have that function return the desired value for each datum, or null if the attribute is not desired for a particular datum, like so:

...
.attr('data-class', function(d) {
    return 'data-class' in d ? d['data-class'] : null;
});

If your function returns null, the attribute is not added. You can even combine several attributes into one call by providing a map of attr names to functions like so:

...
.attr({
    'data-class': function(d) {
        return 'data-class' in d ? d['data-class'] : null;
    }, 
    'data-hide': function(d) {
        return 'data-hide' in d ? d['data-hide'] : null;
    },
    'data-ignore': function(d) {
        return 'data-ignore' in d ? d['data-ignore'] : null;
    }
});

or if you’re like me and would rather not type so much, you can reduce the list of attribute names into the appropriate map:

...
.attr(['data-class', 'data-hide', 'data-ignore'].reduce(function(result, attr) {
    result[attr] = function(d) {
        return attr in d ? d[attr] : null;
    }
    return result;
}, {}));

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)