Pauline Pauline - 1 month ago 7
Javascript Question

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

Answer

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, e.g. with productsById["2"] in this example.

Comments