The nest.object() function in D3.js is used to apply the nest operator to the given array and returns the nested object of key-value pair.
Syntax:
nest.object( array )
Parameters: This function accepts single parameter as mentioned above and described below:
- Array: This parameter holds the array of objects.
Return Value: It returns the object.
Below are a few examples of the above function
Example 1: When no duplicate key exists.
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"      </ 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 > |
Output:
Example 2: When duplicate keys exist and accessing those keys that does not exist when accessed, outputs undefined.
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"      </ 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 > |
Output: