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.
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())));
The code (partial):
let data = new Map(JSON.parse(localStorage.testMusic));
//let data = localStorage.getItem("testMusic");
d3.select("#demo1")
.selectAll("rect")
.data(data,function(d) { return d.key})
.enter()
.append('rect')
...
I tried this also:
.data(d3.keys(data))
but when I step into that d3 function, it doesnt recognized them either.
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; }
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.