Check if d has variable in function (d) {...} in D3

I am creating an array of objects to create a legend in D3. Some of these objects will have certain variables, while other objects will not have these variables. Instead, they should just use the default.

How do I check if a variable exists d.text

? I would like to do this instead of having blank lines in all of my objects that use the default.

    var size_link_data = [{
                percentage : 0.5,
                roundoff : 2,
                recordType: 0,
                text: "a calls b the most"
            }, {
                percentage : 0.5,
                roundoff : 2,
                recordType: 1,
                text: ""
            }, {
                percentage : 0.3,
                roundoff : 1,
                recordType: 1,
                text: ""
            },
            {
                percentage : 0.1,
                roundoff : 1,
                recordType: 1,
                text: ""
            }
        ]

...

legened_next_section.append('text')
    .attr('x', 35)
    .attr('y', function (d, i) {
            return i * 20;          })
    .text(function (d) {
        return d.text != ""? d.text : d.percentage;
    })
    .style('fill', '#757575');

      

+3


source to share


1 answer


You can check if a property is defined. If present, it will use the property text

, otherwise it will be the default percentage

.

.text(function (d) {
    return typeof(d.text) !== "undefined" ? d.text : d.percentage;
})

      



The example below typeof(size_link_data[0].text)

will string

, while typeof(size_link_data[1].text)

will return undefined

.

var size_link_data = [{
            percentage : 0.5,
            roundoff : 2,
            recordType: 0,
            text: "a calls b the most"
        }, {
            percentage : 0.5,
            roundoff : 2,
            recordType: 1
            //No 'text' property
        }
    ];

      

+2


source







All Articles