I'm trying to set the datum of svg rectangles using a js Map, but it isnt working. I think the "d.key" is wrong but not sure. I want the map key to be the data at this point. I'm not getting any errors, it's just not creating them.
The data:
const music = new Map();
music.set("2345",{str:"4",fret:"6"});
music.set("5478",{str:"5",fret:"2"});
music.set("4317",{str:"4",fret:"3"});
music.set("3455",{str:"5",fret:"12"});
localStorage.setItem("testMusic",JSON.stringify(Array.from(music.entries())));
EDIT: Not working either. Does not create any rect on svg with id of demo1. I know they would overlap at this point. Also hovering over d in chrome dev tools shows nothing. data is available The code:
function createNoteRectOnStaff()
{
let data = new Map(JSON.parse(localStorage.testMusic));
d3.select("#demo1")
.selectAll("rect")
.data(data,d=>d)
.enter()
//.join("rect")
.append("rect")
//.attr('id',d=> d[0])
.attr('x', 30)
.attr('y', 60)
.attr('width', 30)
.attr('height', 60)
.attr('stroke', 'green')
.attr('stroke-linecap', 'butt')
.attr('stroke-width', '1')
.attr('fill', 'black')
}
...
I tried this also:
.data(d3.keys(data))
but when I step into that d3 function, it doesnt recognized them either.
CodePudding user response:
You can use data(music) or data(music, d => d) and extract data from the Map per the example below.
const music = new Map();
music.set("2345",{str:"4",fret:"6"});
music.set("5478",{str:"5",fret:"2"});
music.set("4317",{str:"4",fret:"3"});
music.set("3455",{str:"5",fret:"12"});
d3.select("body")
.selectAll(".item")
.data(music, d => d) // or just .data(music)
.enter()
.append("p")
.text(d => {
const key = d[0];
const str = d[1].str;
const fret = d[1].fret;
return [key, str, fret].join(" : ");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.0/d3.min.js"></script>
In the source for data.js there is a function called arraylike that will return an array from a Map with Array.from(Map) which (I assume) is what is at play here. You can see a simple Array.from(music):
const music = new Map();
music.set("2345",{str:"4",fret:"6"});
music.set("5478",{str:"5",fret:"2"});
music.set("4317",{str:"4",fret:"3"});
music.set("3455",{str:"5",fret:"12"});
console.log(Array.from(music));
.as-console-wrapper { max-height: 100% !important; top: 0; }
