JavaScript:将字典转换为D3.js所需的字典数组格式
Got it, let's get that dictionary into the exact structure your D3.js chart expects. This is a super common conversion, and here's a clean, efficient way to do it in JavaScript:
Step 1: Start with your original dictionary
First, make sure your name-frequency data is a valid JavaScript object (I’ve filled in the truncated entry with a placeholder value):
const nameFrequency = { 'Jay Sekulow': 1, 'Jeff Mason': 1, 'John Bolton': 2, 'John Dowd': 1, 'Jonathan Oatis': 3, 'Michael Cohen': 2, 'Michael Dreeben': 1, 'Mike Pence': 2, 'Patricia Zengerle': 1, 'Paul Manafort': 2, 'Rod Rosenstein': 1, 'Ronald R...': 1 };
Step 2: Convert to D3.js's required array format
Use Object.entries() to break down the dictionary into key-value pairs, then map() to reshape each pair into the object structure D3 needs:
const frequency_list = Object.entries(nameFrequency).map(([text, size]) => ({ text, size }));
What this does:
Object.entries(nameFrequency)turns your dictionary into an array of[name, frequency]pairs.- The
map()function takes each pair and converts it into an object withtext(the name) andsize(the frequency) properties—exactly the structure your D3 chart is looking for.
Result
After running the code, frequency_list will look exactly like this:
[ {"text":"Jay Sekulow","size":1}, {"text":"Jeff Mason","size":1}, {"text":"John Bolton","size":2}, {"text":"John Dowd","size":1}, {"text":"Jonathan Oatis","size":3}, {"text":"Michael Cohen","size":2}, {"text":"Michael Dreeben","size":1}, {"text":"Mike Pence","size":2}, {"text":"Patricia Zengerle","size":1}, {"text":"Paul Manafort","size":2}, {"text":"Rod Rosenstein","size":1}, {"text":"Ronald R...","size":1} ]
This works seamlessly even if you add more name-frequency pairs later—just update the original dictionary and the conversion will handle the rest.
内容的提问来源于stack exchange,提问作者jax

