D3.js中的数组查找

时间:2018-08-24 22:09:54

标签: javascript d3.js

在D3.js(或通常在JavaScript中)中,如果您有类似的数组

var out = [
    {name:"John", car:"bmw", colour:"blue"},
    {name:"Joe", car:"ford", colour:"red"},
    {name:"Anna", car:"honda", colour:"green"},
    {name:"Mary", car:"bmw", colour:"red"},
];

如何获得给定名称的car和/或colour?名称可以被认为是唯一的,并且数组不一定必须是数组,即dict也应该很好

谢谢

2 个答案:

答案 0 :(得分:3)

您可以使用Array.prototype.find()方法,该方法将返回整个对象,包括carcolour和给定的name

示例:

var out = [
    {name:'John', car:'bmw', colour:'blue'},
    {name:'Joe', car:'ford', colour:'red'},
    {name:'Anna', car:'honda', colour:'green'},
    {name:'Mary', car:'bmw', colour:'red'}
];


out.find(function(item) {
    return item.name === 'John'
}

// will return the following:
{ name: 'John', car: 'bmw', colour: 'blue' }

您还可以使用ES6 arrow function来实现相同的目的:

out.find(item => item.name === 'John')
  

以下是Array.prototype.find()的文档。

答案 1 :(得分:2)

尝试d3.map,它将在给定键的情况下返回数据数组中的一项。它的创建过程如下:

 d3.map(array, function(d) { return d.key; });

然后您可以通过以下方式访问地图中的项目:

 map.get("value");

或检查是否存在这样的值:

 map.has("value");

有关更多信息,请参见docs

这是您的数据集示例:

var out = [
    {name:"John", car:"bmw", colour:"blue"},
    {name:"Joe", car:"ford", colour:"red"},
    {name:"Anna", car:"honda", colour:"green"},
    {name:"Mary", car:"bmw", colour:"red"},
];


var map = d3.map(out, function(d) { return d.name; });

// Get items by key:
console.log(map.get("John").car);
console.log(map.get("Anna").colour);

// Check to see if an item exists:
console.log(map.has("Joe"));

// Create a new value and access:
map.set("Ralph", {name: "Ralph",car:"bmw",colour:"red"})
console.log(map.get("Ralph"));
<script src="https://d3js.org/d3.v4.min.js"></script>

当然,您无需为此使用d3,常规的ES6映射(或许多其他选项)可以同样容易地工作:

var out = [
    {name:"John", car:"bmw", colour:"blue"},
    {name:"Joe", car:"ford", colour:"red"},
    {name:"Anna", car:"honda", colour:"green"},
    {name:"Mary", car:"bmw", colour:"red"},
];

var map = new Map(out.map(function(d) {
  return [d.name,d];
}));

console.log(map.get("John"));