所以我有以下巢:
var myNest = [
{"key":"1","values":[...]},
{"key":"2","values":[...]},
{"key":"3","values":[...]},
]
如何使用密钥访问这些元素?
我知道我可以通过索引访问它们
myNext[0] //return elements with key=="1"
myNest[1] //return elements with key=="2"
但我想做的是:
myNest["1"] //return elements with key=="1"
myNest["2"] //return elements with key=="2"
由于
答案 0 :(得分:4)
构建嵌套时使用map()
代替entries()
。你可能做了类似的事情:
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>
&#13;
如果您使用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)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
您可以获得一张地图,您可以通过其直接访问对象,例如在此示例中使用productsById["2"]
。
答案 1 :(得分:1)
你可以使用哈希表,你的对象的键是对象itselft的键。
对于ES6,我建议使用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']);
&#13;