I am very very new to d3.js
. I have parent g container
that looks like so
var g = pieParentG.append("g")
.attr("transform", "translate(" + xVal + "," + yVal + ")")
.selectAll("arc")
.data(pie(dataVal))
.enter()
.append("g")
.attr("class", "arc");
I am trying to add a child text node like so
var textG = g.append("g")
.append("text")
.html(function(d) {
return d.data.zone;
});
However, the dataval array of objects might contain duplicate values. An example of the array is
[{
"count": 1267,
"path": 1,
"zone": "Bandra-Pillers"
},
{
"count": 697,
"path": 2,
"zone": "Bandra-Pillers"
},
{
"count": 560,
"path": 3,
"zone": "Bandra-Pillers"
}
]
the text field should map to this zone field in the array. In case of duplicate values, such as in this case, I want only 1 text element to be appended. Is the Array.filter function an option? If yes, then where do I use it?
the text field should map to this zone field in the array. In case of duplicate values, such as in this case, I want only 1 text element to be appended. Is the Array.filter function an option? If yes, then where do I use it?
Actually if you want to return only 1 object matching this zone
from your array, you can't use .filetr()
as it will return alll the elements that have the same zone
.
You can use Array#find()
it will return only the first object
that pass the condition:
The
find()
method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
This is how should be your code:
var myObj = dataVal.find(function(item) {
return item.zone === "Bandra-Pillers";
});
Demo:
var dataVal = [{ "count": 1267, "path": 1, "zone": "Bandra-Pillers" }, { "count": 697, "path": 2, "zone": "Bandra-Pillers" }, { "count": 560, "path": 3, "zone": "Bandra-Pillers" } ]; var myObj = dataVal.find(function(item) { return item.zone === "Bandra-Pillers"; }); console.log(myObj);
Edit:
You can call it in the callback function of .html()
like this:
var textG = g.append("g")
.append("text")
.html(function(d) {
return dataVal.filter(function(item){
return item.zone === zone; //Pass zone variable here
})[0].data.zone;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.