简体   繁体   中英

Get value from json value key pair with D3

I'm using D3 to draw lines from a json array. I can get the values from it for the x and y coordinates, but I'm trying to get a line name and assign it to the path object id but getting all sort of [object object} errors. The array I'm using is: [ {name: "line1", x: 1, y: 1},{name: "line1", x: 1, y: 2},{name: "line1", x: 1, y: 5},]

It's the same for the different lines and the name is repeated as I may need it in each data point.

The code is:

var width = 500,
        height = 500,
        margin = 50,
        x = d3.scale.linear()
                .domain([0, 10])
                .range([margin, width - margin]),
        y = d3.scale.linear()
                .domain([0, 10])
                .range([height - margin, margin]);


var actionsD3 = [
[ {name: "line1", x: 1, y: 1},{name: "line1", x: 2, y: 2},{name: "line1", x: 3, y: 5},]
];

var line = d3.svg.line()
        .x(function(d){return x(d.page);})
        .y(function(d){return y(d.characterid);});

var lineName = d3.select()
        .jsonData(function(d){return (d.name);});

svg.attr("height", height)
        .attr("width", width);

function render(data) {
        svg.selectAll("path")
                        .data(data)
                .enter()
                        .append("path")
                        .attr("class", "line")
                        .attr("id",function(d){return lineName(d);})
                        .attr("d", function(d){return line(d);});
}

render(actionsD3);

What I'd like is the same as for the line where I get the value for x and y with dx and dy But I seem to always get the pair or an array.

Thanks

The code you've posted doesn't work, but from your description it would be something like .attr("id", function(d) { return d[0].name; }) . The idea is that you're passing in an array that designates the line and get the ID from the first point of the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM