當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


d3.js nest.object()用法及代碼示例

D3.js中的nest.object()函數用於將nest運算符應用於給定數組,並返回鍵值對的嵌套對象。

用法:

nest.object( array )

參數:該函數接受上述和以下描述的單個參數:

  • Array:此參數保存對象數組。

返回值:它返回對象。

以下是上述函數的一些示例



範例1:不存在重複 key 時。

HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content= 
        "width=device-width, initial-scale=1.0"> 
  
    <style> 
        .originalColor { 
            height:100px; 
            width:100px; 
        } 
  
        .darkerColor { 
            height:100px; 
            width:100px; 
        } 
    </style> 
</head> 
  
<body> 
  
    <!-- Fetching from CDN of D3.js -->
    <script type="text/javascript" 
        src="https://d3js.org/d3.v4.min.js"> 
    </script> 
      
    <script> 
        // Forming the array of objects 
        let array = [ 
            { car:"car1" }, { model:"model1" }, 
            { car:"car2" }, { model:"model1" }, 
            { car:"car3" }, { model:"model2" }, 
            { car:"car4" }, { model:"model2" }, 
            { car:"car5" }, { model:"model3" } 
        ] 
        let data = d3.nest() 
            .key(function (d) { return d.car; }) 
            .key(function (d) { return d.model; }) 
            .object(array) 
        console.log("Type is:", typeof array) 
        console.log(data); 
    </script> 
</body> 
  
</html>

輸出:

範例2:當存在重複的鍵並訪問那些在訪問時不存在的鍵時,輸出未定義。

HTML

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content= 
        "width=device-width, initial-scale=1.0"> 
  
    <style> 
        .originalColor { 
            height:100px; 
            width:100px; 
        } 
  
        .darkerColor { 
            height:100px; 
            width:100px; 
        } 
    </style> 
</head> 
  
<body> 
    <!-- Fetching from CDN of D3.js -->
    <script type="text/javascript" 
        src="https://d3js.org/d3.v4.min.js"> 
    </script> 
      
    <script> 
        // Forming the array of objects 
        let array = [ 
            { car:"car1" }, { model:"model1" }, 
            { car:"car3" }, { model:"model1" }, 
            { car:"car3" }, { model:"model2" }, 
            { car:"car3" }, { model:"model2" }, 
            { car:"car5" }, { model:"model3" } 
        ] 
        let data = d3.nest() 
            .key(function (d) { return d.car; }) 
            .key(function (d) { return d.model; }) 
            .key(function (d) { return d.car; }) 
            .object(array) 
        console.log(data); 
        console.log(data.car1); 
  
        // Key does not exists so  
        // output is undefined 
        console.log(data.car2); 
        console.log(data.car3); 
    </script> 
</body> 
  
</html>

輸出:




相關用法


注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 D3.js nest.object() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。