简体   繁体   中英

Accessing nest elements by their keys with d3.js

So I have the following nest:

var myNest = [
  {"key":"1","values":[...]},
  {"key":"2","values":[...]},
  {"key":"3","values":[...]},
]

How can I access these elements using their keys?

I know I can access them by their index

myNext[0] //return elements with key=="1"
myNest[1] //return elements with key=="2"

But what I would like to do is:

myNest["1"] //return elements with key=="1"
myNest["2"] //return elements with key=="2"

Thanks

Use map() instead of entries() when building your nest. You probably did something similar to this:

 var products = [{ "id": 1, "name": "Cat Hat", "price": 49 }, { "id": 2, "name": "Unicorn Boots", "price": 139 }, { "id": 3, "name": "Pink Woolly Jumper", "price": 34 }]; var productsById = d3.nest() .key(function(p) { return p.id; }) .entries(products); console.log(productsById) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

If instead you use map() :

 var products = [{ "id": 1, "name": "Cat Hat", "price": 49 }, { "id": 2, "name": "Unicorn Boots", "price": 139 }, { "id": 3, "name": "Pink Woolly Jumper", "price": 34 }]; var productsById = d3.nest() .key(function(p) { return p.id; }) .map(products); console.log(productsById) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

You get a map where you can access objects by their key directly, eg with productsById["2"] in this example.

You could us a hash table, where the key of your object is the key for the object itselft.

For ES6 I suggest to use a Map:

 var myNest = [{ key: "1", values: [1, 4] }, { key: "2", values: [2, 5] }, { key: "3", values: [3, 6] }], hash = Object.create(null); myNest.forEach(function (a) { hash[a.key] = a; }); console.log(hash['2']); 

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