简体   繁体   English

使用 Javascript Map 作为 D3 中的数据

[英]Using a Javascript Map as data in D3

I'm trying to set the datum of svg rectangles using a js Map, but it isnt working.我正在尝试使用 js Map 设置 svg 矩形的基准,但它不起作用。 I think the "d.key" is wrong but not sure.我认为“d.key”是错误的,但不确定。 I want the map key to be the data at this point.我希望 map 键成为此时的数据。

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.但是当我走进那个 d3 function 时,它也没有认出它们。

You can use data(music) or data(music, d => d) and extract data from the Map per the example below.您可以使用data(music)data(music, d => d)并根据以下示例从Map中提取数据。

 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.在 data.js 的源代码中,有一个名为arraylike的 function ,它将从Map中返回一个带有Array.from(Map)的数组,这(我假设)是在这里起作用的。 You can see a simple Array.from(music) :你可以看到一个简单的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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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