代码之家  ›  专栏  ›  技术社区  ›  Aenaon

D3.js中的数组查找

  •  1
  • Aenaon  · 技术社区  · 7 年前

    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 回复  |  直到 7 年前
        1
  •  2
  •   Andrew Reid    7 年前

     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"));
        2
  •  3
  •   tobias    7 年前

    你可以用 Array.prototype.find() 方法,它将返回整个对象,包括 car , colour ,以及给定的 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()